简体   繁体   中英

Json_decode is not working

I can see my json formatted response but once I try to decode and print specific value then it simply goes silent without printing error/null. tried almost all methods to access json.. Error reporting is on

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true); // without true tried
echo $response; //prints json response
echo $result->count; // does not work here $result['count'] tried

JSON response as below:

{"status":200,"message":"data found","data":{"count":"1050"}}

You can do something like this to get individual values,

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true);
echo $result['status'] . "<br />";  // 200
echo $result['message'] . "<br />"; // data found
echo $result['data']['count'] . "<br />";  // 1050

Output:

200
data found
1050

In json_decode() you are telling the function to create an associative array instead of an object by setting the 2nd parameter to true. To make it an object just use:

$result = json_decode($response);

Otherwise, with your current methodology you can access the variable by using $result['count'];

json_decode function has boolean when TRUE will returned objects will be converted into associative arrays. So if you would like to use objects instead of arrays remove TRUE

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response);
echo $response; //prints json response
echo $result->count; // should work

or you can use arrays instead of objects

$url = 'localhost:8080/app/api/Api.php?name=c';
$client = curl_init($url);
curl_setopt($client, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($client);
$result = json_decode($response, true);
echo $response; //prints json response
echo $result['count'];

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