0

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:

enter image description here

BLAKE
  • 149
  • 1
  • 15
  • 1
    `json_decode($response, true);` - The second argument `true` tells the function to return it as associative arrays instead of objects. If you want to use objects, removing `true` and test again. You can also do `var_dump($data)` to see what the variable actually contains. – M. Eriksson Oct 28 '19 at 15:05
  • @MagnusEriksson That did it. Thank you very much! If you want to post that as an answer I will accept it. – BLAKE Oct 28 '19 at 15:07
  • 1
    Possible duplicate of [json\_decode() returning error "Notice: Trying to get property of non-object"](https://stackoverflow.com/questions/25195010/json-decode-returning-error-notice-trying-to-get-property-of-non-object) – M. Eriksson Oct 28 '19 at 15:07
  • I added it as a duplicate instead, since it's already been asked and answered. – M. Eriksson Oct 28 '19 at 15:08

0 Answers0