I am using cURL and PHP to make a request to a test API to return a list of users but I get the following error:
PHP Notice: Trying to get property 'id' of non-object
Not sure where I am going wrong.
Here is my code
<?php
// I am using the JSONPlaceholder website as a test API
$url = 'https://jsonplaceholder.typicode.com/users';
// Initial a new cURL session
$request = curl_init($url);
// Return request as string
curl_setopt($request, CURLOPT_RETURNTRANSFER, true);
// Run cURL / execute http request
$response = curl_exec($request);
// Close the cURL resource
curl_close($request);
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
print $response->id . "\n";
print $response->name . "\n";
print $response->username . "\n";
}
?>
you have to loop through the response:
if ($response === false) {
print "Could not make successful request\n";
} else {
$response = json_decode($response);
foreach ($response as $item) {
print $item->id . "\n";
print $item->name . "\n";
print $item->username . "\n";
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.