0

I have the below code and what I am trying to do is get the json value from "total_reviews" into a php variable which we can call $total_reviews.

however what is happening is i am getting an error that says

Notice: Undefined property: stdClass::$total_reviews

Here is my code

//URL of targeted site  
$url = "https://api.yotpo.com/products/$appkey/467/bottomline";  
//  Initiate curl
$ch = curl_init();

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
$data = json_decode($result);

echo "e<br />";
echo $data->total_reviews; 


// close curl resource, and free up system resources  
curl_close($ch);  
?>

If I print_r the result I have the below print out

{"status":{"code":200,"message":"OK"},"response":{"bottomline":{"average_score":4.2,"total_reviews":73}}}

2 Answers 2

3

If you want the JSON data as an array then use the second parameter on json_decode() to make it convert the data to an array.

$data = json_decode($result, true);

If you want the JSON data as it was passed to you and I assume that is as an Object then use

$data = json_decode($result);

echo "<br />";
echo $data->total_reviews; 

The json_decode() manual page

But either way, if this is your JSON String,

{"status":
    {
        "code":200,
        "message":"OK"
    },
"response":
    {
        "bottomline":
            {
                "average_score":4.2,
                "total_reviews":73
            }
    }
}

then the total_reviews value would be

echo $data->response->bottomline->total_reviews;

or if you used parameter 2 to convert a perfectly good object into an array

echo $data['response']['bottomline']['total_reviews'];
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Riggsfolly that helped
Totally my pleasure
1

json_decode() defaults to extracting into a stdClass object. If you want an array, pass a truthy value as the second argument:

$data = json_decode($result, true);

1 Comment

I just updating my code in the original post. however am getting an error that says Notice: Undefined property: stdClass::$total_reviews

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.