We help IT Professionals succeed at work.

PHP Curl Json issues

qvfps asked
I am trying to write a small application in PHP do download some content using curl in json format and process it.     Below is the data returned via curl and the error message I get when trying to walk through it.   I am sure it is something small I have done wrong I just cant see it.  

I appreciate any suggestions.  

$url = "https://website/records";
$apikey = '11111111111111111111111';
$ch = curl_init( $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-API-KEY: ' .$apikey, 'Content-Type: application/json' , 'Accept: application/json'));
$myout = curl_exec($ch);

//$result = json_decode(json_decode($myout,true));
$result = json_decode($myout);
echo $myout;
$myResult = $result;

foreach($myResult as $value){
       echo $value->name . ",  " , $value->gender . "<br>\n";



Invalid argument supplied for foreach()
Watch Question

Most Valuable Expert 2018
Distinguished Expert 2019
Hey there,

Your JSON looks like it has a property called items that is an array of objects, so you'd need to loop through items. Also, you seem to be trying to read properties called name and gender, but your JSON doesn't have those properties at all, so not sure what you're actually trying to do:

$result = json_decode($myout);
foreach($result->items as $item) {
    echo $item->TicketID . "<br>";
    echo $item->WorkHoursID . "<br>";

Open in new window


This is my first time trying to use curl and json so it was just me being an idiot and copying an example verbatim and wondering why it didn't work with different input.     I should have looked at the sample data and realized Name and Gender were items and not default properties as I was assuming for some unknown reason.      

Thanks for the help