Read curl php result - php

I'm doing a curl and getting the JSON result as:
$data = json_decode($result, true);
var_dump($data);
$data = $data["data"];
echo $data;
However, the echo of $data is "{". If I do a var_dump before assigning again the variable I see:
string(727796) "{"data":["base64_image1", "base64_image2",... ]}"
Why am I not able to access the data list? I just want to do a foreach over this list, but I cannot.

output is json so try to json_decode() again

Related

Having trouble accessing values from json_decode

I have a json object from a curl get request.
// Curl Stuff
$resp = curl_exec($curl);
{"food": {"id":585897,"foodGroup":"meats","calories":1109,"foodTier":30}}
I saved it in a variable with json_decode
$data = json_decode($resp, TRUE);
I've tried accessing the data in a couple ways but I get no response
echo $data[0][1];
echo $data[0]['id'];
Also if someone can point me in the right direction of looping through this data I would appreciate that.
With the true parameter in your json_decode, you have associative array, so it must be:
echo $data['food']['id'];
Get the id by numeric:
$da = array();
foreach($data as $key=>$val){
$da[$key] = array_values($val);
}
print_r($da);
echo $da['food'][0];

Problems parsing JSON with PHP (CURL)

I am trying to access the value for one of the currencies (e.g. GBP) within the "rates" object of the following JSON file:
JSON file:
{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}
This was my approach:
PHP (CURL):
$url = ...
// initialize CURL:
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// get the (still encoded) JSON data:
$json = curl_exec($ch);
curl_close($ch);
// store decoded JSON Response in array
$exchangeRates = (array) json_decode($json);
// access parsed json
echo $exchangeRates['rates']['GBP'];
but it did not work.
Now, when I try to access the "timestamp" value of the JSON file like this:
echo $exchangeRates['timestamp'];
it works fine.
Any ideas?
Try removing (array) in front of json_decode and adding true in second parameter
Here is the solution.
$exchangeRates = (array) json_decode($json,TRUE);
https://ideone.com/LFbvUF
What all you have to do is use the second parameter of json_decode function.
This is the complete code snippet.
<?php
$json='{
"success":true,
"timestamp":1430594775,
"rates":{
"AUD":1.273862,
"CAD":1.215036,
"CHF":0.932539,
"CNY":6.186694,
"EUR":0.893003,
"GBP":0.66046,
"HKD":7.751997,
"JPY":120.1098,
"SGD":1.329717
}
}';
$exchangeRates = (array) json_decode($json,TRUE);
echo $exchangeRates["rates"]["GBP"];
?>

Parse Data from JSON URL

I'm trying to get data onto my website by parsing data from a JSON format. The URL is http://api.bfhstats.com/api/onlinePlayers and I'm trying to output for example the currently players online on PC.
Here's the current code I have:
<?$json = file_get_contents("http://api.bfhstats.com/api/onlinePlayers");
$data = json_decode($jsondata, true);
echo $data->pc->peak24;?>
I thought this would work, however it's not displaying anything. I am very new to parsing JSON data so if someone could explain what I'm doing wrong that would be brilliant.
change:
$data = json_decode($jsondata, true);
to
$data = json_decode($json, true);
Also, json_decode returns an array so use:
echo $data['pc']['peak24'];
to access the data.
You first call the variable $json but then use $jsondata in json_decode.
You are missing the foreach cycle to fetch the two dimensional array $data:
<?php
$json = file_get_contents("http://api.bfhstats.com/api/onlinePlayers");
$data=array();
$data = json_decode($json, true);
//print_r ($data);
foreach ($data as $pc) {
echo $pc["peak24"]."<br>";
}
?>
Check the $json and $jsondata that have different name but should be the same.

How to output json data in array using curl

I have code here that will get json data using curl. Now I want to echo all data. This will show no output.
<?php
$json = file_get_contents('myurl');
$data = json_decode($json);
print_r($data);
?>
This is json coming from my url:
({"Response_Code":"0000","ResultMobilePrefix":["0917","0905","0906","0915","0916","0926","0927","0937","0935","0817","0936","0922","0923",
"0932","0933","0934","0942","0943","0907","0908","0909","0910","0912","0918","0919","0920","
0921","0928","0929","0930","0938","0939","0948","0949","0925","0989","0999","0947","0998","
0946","0975","0977"]});
All you need is
echo json_encode($json);
Use true to convert it into array;
$data = json_decode($json,true);
echo '<pre>';
print_r($data);
for displaying json in format use json_encode() and for proper format use JSON_PRETTY_PRINT
header('Content-type: application/json');
echo json_encode($json,JSON_PRETTY_PRINT);
you need to get rid of the bracket and semicolon on the JSON file first before you can use the json_decode();
<?php
$json = file_get_contents('myurl');
//remove the brackets
$json = str_replace("(", "", $json);
$json = str_replace(")", "", $json);
//remove the semicolon
$json = str_replace(";", "", $json);
$data = json_decode($json);
print_r($data);
?>
this is a bit ugly, but hope you get the idea, you need to remove that character first
I just want to add to what Manish has explained above. This is what PHP Docs say about the second parameter:
When TRUE, returned objects will be converted into associative arrays.
else you will simply get a stdclass object
The problem is the URL does not return a valid Json
you could simply try
var_dump($data);
this will return null because it's not a valid json see json_decode
this will work
$json = file_get_contents('myurl');
$json = preg_replace('/[ ]{2,}|[\t\n\r\(\)\;]/', '', trim($json));
$data = json_decode($json);
print_r($data);

get Specific JSON Response Value

json response as below:
{"Success":true,"ErrorCode":0,"UserInformation":{"UserID":"19"}......
how do I get the UserID value by using json_decode?
I tried the below code with no luck.
$Response = json_decode($Response[2]);
echo $Response[0][0][0];
This should work:
<?php
$json = '{"Success":true, "ErrorCode":"0","UserInformation":{"UserID":"19"}}';
$response = json_decode($json, true);
echo $userId = $response["UserInformation"]["UserID"];
?>
Please check the PHP documentation of json_decode at http://php.net/json_decode
You can use object as well if you skip the second parameter of the json_decode function.

Categories