Skip to content
Advertisement

PHP Notice: Trying to get property ‘id’ of non-object. How to resolve?

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 requestn";
} else {
    $response = json_decode($response);
    print $response->id . "n";
    print $response->name . "n";
    print $response->username . "n";
}
?>

Advertisement

Answer

you have to loop through the response:

if ($response === false) {
    print "Could not make successful requestn";
} else {
    $response = json_decode($response);

    foreach ($response as $item) {
        print $item->id . "n";
        print $item->name . "n";
        print $item->username . "n";
    }
    
}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement