简体   繁体   中英

get json string into php variables

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}}}

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'];

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);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM