I am attempting to request data from a url and am having success for most endpoints except for one. Throughout my troubleshooting, I can retrieve the text and display it in the browser, however, when I try to store it as an object, I get nothing. It actually still stores as a string. I would like to iterate through the object so that I can run calculations on the contents.
Is it because the JSON string is malformed? If so, how do I correct? I have tried a variety of solutions with no success.
Important to note that gzip is required, for that reason I have included 'ob_gzhandler'. the contents only echos when I use gzhandler.
THE ECHOS IN THE FUNCTION ARE FOR TROUBLESHOOTING PURPOSES. THEY ILLUSTRATE WHERE STRINGS ARE BEING PRODUCED AND NOT OBJECTS.
function CallAPI_oanda_v20($instruments)
{
$curl = curl_init();
$url = 'https://api-fxtrade.oanda.com/v3/instruments/'.$instruments.'/positionBook';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPGET,TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Authorization: <USE MY API KEY>'));
$response = curl_exec($ch);
echo gettype($response); //returns "string"
$json = json_decode($response, true);
echo gettype($json); //returns "NULL"
curl_close($ch);
return $json;
}
$call = CallAPI_oanda_v20("GBP_USD");
ob_start('ob_gzhandler');
//$output = ob_get_contents();
echo $call->positionBook; //returns an error:Trying to get property 'positionBook' of non-object
echo gettype($output); //THIS WILL RETURN "string".
$jsonIterator = new RecursiveIteratorIterator(
new RecursiveArrayIterator(json_decode($output, TRUE)),
RecursiveIteratorIterator::SELF_FIRST);
foreach ($jsonIterator as $key => $val) {
if(is_array($val)) {
echo "$key:\n";
} else {
echo "$key => $val\n";
}
}
In order to troubleshoot that the call is correct, I echo the contents by graying out the following line:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
Here is the json string that prints:
{"positionBook":{"instrument":"GBP_USD","time":"2019-09-02T00:00:00Z","unixTime":"1567382400","price":"1.21584","bucketWidth":"0.00050","buckets":[{"price":"1.19950","longCountPercent":"0.0189","shortCountPercent":"0.0189"},{"price":"1.20000","longCountPercent":"0.0000","shortCountPercent":"0.0189"},{"price":"1.20100","longCountPercent":"0.0000","shortCountPercent":"0.0189"},{"price":"1.20150","longCountPercent":"0.0000","shortCountPercent":"0.0757"}]}}
$callshould in theory be an object.echo $call->positionBook;? If that doesn't work, what about justecho $call;?ob_get_contentsreturns a string, instead just use$call, which has your object