We help IT Professionals succeed at work.

PHP Curl Json issues

qvfps
qvfps asked
on
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.  

<?php
$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);
curl_close($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";
}

?>

{"items":[{"TicketID":41,"WorkHoursID":53,"StartWorkHour":"2019-09-16T13:33:11Z","EndWorkHour":"2019-09-16T13:33:13Z","TechnicianContactID":2,"Billiable":true,"OnCustomerSite":false,"Description":null,"TechnicianFullName":"Tech1","TechnicianEmail":"Tech1@support.com"},{"TicketID":41,"WorkHoursID":82,"StartWorkHour":"2019-08-05T15:23:21Z","EndWorkHour":"2019-08-05T15:26:33Z","TechnicianContactID":7,"Billiable":true,"OnCustomerSite":false,"Description":null,"TechnicianFullName":"Tech2","TechnicianEmail":"Tech2@support.com"}],"totalItemCount":2,"page":1,"itemsInPage":10,"totalPages":1,"prevLink":"","nextLink":""}


Invalid argument supplied for foreach()
Comment
Watch Question

CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019
Commented:
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

Author

Commented:
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