1

I am writing a script that does foreign exchange using an API to do it in realtime.

I presume that the problem is in my implementation of curl, as I get no output from this :

$currencyBase    = "USD";
$currencyForeign = "EUR";
$url             = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=' . $currencyBase . '&to_currency=' . $currencyForeign . '&apikey=KCUGBA9AP3Z1E2P8';

echo $currencyBase;

// create curl resource
$c = curl_init($url); //Initialize a cURL session
curl_setopt($c, CURLOPT_HEADER, 0);  //Set an option for a cURL transfer
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); //Set an option for a cURL transfer                           
$this->fxRate = doubleval(curl_exec($c));  
curl_close($c);  //Close a cURL session

I have hardcoded

$currencyBase    = "USD";
$currencyForeign = "EUR";

for debugging and I have also tried print_r($c) to see if I'm passing anything but I still get no output.

I know that my API call works because I have tried the link with entered USD and EUR and I get a response when I enter it in the browser as follows:

https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency=USD&to_currency=EUR&apikey=KCUGBA9AP3Z1E2P8

But I always get an empty response when I print the output from the script.

3
  • Are you decoding the result anywhere? That URL returns JSON for me, and you're trying to convert it to a float. Commented Nov 3, 2017 at 17:31
  • You should keep your API key private - maybe best to cancel and request a new one. I ran your copied code on my server to live test (unintentionally) with YOUR key (before Blues answer). Commented Nov 3, 2017 at 19:01
  • I am only using it for testing, but yes I will request a new one. Thank you! Commented Nov 3, 2017 at 19:09

1 Answer 1

1

Your problem is this part of the code: $this->fxRate = doubleval(curl_exec($c));

curl_exec returns a string (which happens to be json), which you are casting to doubleval and that results in 0. Try it like this instead:

$this->fxRate = json_decode(curl_exec($c))->{"Realtime Currency Exchange Rate"}->{"5. Exchange Rate"};

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.