I am running into an error where I am getting data in JSON. When I try to use json_decode
and then echo $data
I get error where it is telling me that I am trying to get a property of a non-object when the console is clearly showing that it is an object.
Code:
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://jsonplaceholder.typicode.com/comments",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo '<script> console.log( ' . $response . ');</script>';
}
$data= json_decode($response, true);
echo '<script> console.log( ' . $data[0]->body . ');</script>';
Error: Notice: Trying to get property of non-object in C:\xampp\xampp\htdocs\dashboard\path\jsonObjects.php on line 40
Console Showing JSON Data: