Looping through JSON with PHP to get children Looping through JSON with PHP to get children json json

Looping through JSON with PHP to get children


It looks like your cURL request is to blame, you're not telling cURL you're expecting a response, so cURL just passes back a boolean success for your initial request, it sent it successfully.

From the PHP curl_exec page.

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

It's succeeding, but you're not telling it you're expecting a response, so it returns TRUE.

Try this:

$url = 'https://myapi.com/api?token=xxx&from_date='.$from_date.'&to_date='.$to_date;$options = array(    CURLOPT_RETURNTRANSFER => true,   // return web page <-- This is the important one that tells cURL you want a response.    CURLOPT_HEADER         => false,  // don't return headers    CURLOPT_FOLLOWLOCATION => true,   // follow redirects    CURLOPT_MAXREDIRS      => 10,     // stop after 10 redirects    CURLOPT_AUTOREFERER    => true,   // set referrer on redirect    CURLOPT_CONNECTTIMEOUT => 120,    // time-out on connect    CURLOPT_TIMEOUT        => 120,    // time-out on response); $ch = curl_init($url);curl_setopt_array($ch, $options);$result = curl_exec($ch);curl_close($ch);

2nd error

Now we've got cURL working lets address the result. Remember that when JSON is converted each brace ({) will produce an object, and each square bracket ([) will produce an array. So if we follow your JSON we can see that you will get an object back, containing the property results. You can access that using $responseData->results.

In your second foreach you're trying to access the property of an object. Results isn't an object, it's an array (look at your JSON, it contains a [, so it's an array). To get the rates follow through the JSON string and you'll see you need to do this:

foreach($responseData->results[0]->rates as $rate) {    echo $rate->id . "\n";}