Reputation:
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"}}
Upvotes: 0
Views: 577
Reputation: 16963
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
Upvotes: 1
Reputation: 269
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'];
Upvotes: 0
Reputation: 382
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'];
Upvotes: 0