Php Json Decode - Display value of second level items - php

I'm trying to decode JSON format
My API Endpoint is https://api.reliableserver.host/api/landings
And this is the output
{
"success": true,
"data": [
{
"id": 1,
"primary_balance": "$4,184.37",
"primary_currency": "USD",
"secondary_balance": "¥0",
"secondary_currency": "JPY",
"tertiary_balance": "฿0.00",
"tertiary_currency": "THB",
"first_language": "ไทย",
"second_language": "English",
"footer_text": "a",
"created_at": "2020-10-26T07:45:49.000000Z",
"updated_at": "2020-10-28T05:31:04.000000Z",
"deleted_at": null
}
],
"message": "Landings retrieved successfully"
}
I need to echo individual values, for example: Primary Balance: $4,184.37
I tried using this:
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode($url);
echo $obj>primary_balance;
But it didnt work, kindly guide me what am I doing wrong.

You can do this way :
$url = '{"success": true,"data": [{"id": 1,"primary_balance": "$4,184.37","primary_currency": "USD","secondary_balance": "¥0","secondary_currency": "JPY","tertiary_balance": "฿0.00","tertiary_currency": "THB","first_language": "ไทย","second_language": "English","footer_text": "a","created_at": "2020-10-26T07:45:49.000000Z","updated_at": "2020-10-28T05:31:04.000000Z","deleted_at": null}],"message": "Landings retrieved successfully"}';
$obj = json_decode($url, true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37
Above code tested here
You need file_get_contents() method to get the JSON data from your given URL.
$url = "https://api.reliableserver.host/api/landings";
$obj = json_decode(file_get_contents($url), true);
echo $obj['data'][0]['primary_balance'];
// output $4,184.37

Basically, you are not calling that api anywhere. If it is an open endpoint (without auth or headers, you can do file_get_contents() or I suggest you to use curl.
Also, you need to check on response data structure, it has a 'data' key which is an array. so you need to use foreach to iterate on the 'data' key.
I have given a sample answer that should work if there is only 1 item in data.
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp);// will return in object form
echo $obj->data[0]->primary_balance;
or
$url = "https://api.reliableserver.host/api/landings";
$resp = file_get_contents($url);
$obj= json_decode($resp, true); // will return in array form
echo $obj['data'][0]['primary_balance'];
json_decode()

Related

How to take selected value from json response laravel?

I want to get price of btc to usd using coinmarketcap's API.
$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
Getting 200 Ok response
"data": {
"symbol": "BTC",
"id": "1",
"name": "Bitcoin",
"amount": 50,
"last_updated": "2018-06-06T08:04:36.000Z",
"quote": {
"USD": {
"price": 284656.08465608465,
"last_updated": "2018-06-06T06:00:00.000Z"
},
I want to get Price value from usd but its not working when i tried
$examount = $type->USD->price;
Since you are using
$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
It means that your object is converted to associative array,
to access the price use:
$type['data']['quote']['USD']['price'];
You should be good to go.
Edit
In case $type contains more than one element, you will need to loop them.
foreach($type['data'] as $singleQuote){
$price = $singleQuote['quote']['USD']['price'];
echo 'Quote for: '.$singleQuote['symbol'].' in USD: '.$price.'<br/>';
}
Because you are passing 2nd param true that will convert it to associative array:
$response = curl_exec($curl); // Send the request, save the response
$type = json_decode($response,true);
$examount = $type['data']['quote']['USD']['price'];
I hope above will solve your problem as per the documentation of coinmarketcap (https://coinmarketcap.com/api/documentation/v1/#section/Endpoint-Overview)
the problem was cuased by the $request was returning null all of above are correct also

php read content from json file and then update

I have the following data from an api call:
$userId = 1234; and $accessToken = 6789;. I want to write this to a json file called users.json.
Following this I make another api call and receive the following data:
$userId = 5678; and $accessToken = 0123;.
I then want to add this to the json file so that it looks like this:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
},
]
My code for writing to the json file looks like this. The $userId and $accessToken are defined elsewhere and are returning the correct values:
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
print_r($tempArray); // this doesn;t show anything as the users.json file contains `null`
array_push($tempArray, $userId);
array_push($tempArray, $accessToken);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
Unfortunately this isn't working. When I view the json file it just contains null Can anyone see any error with my code?
Thanks Raul
Your code is wrong. Correct it to look like this
<?php
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
if(empty($tempArray)){
$tempArray = [];
}
$newData = [
"userId" => $userId,
"accessToken" => $accessToken
];
array_push($tempArray, $newData);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
This will definitely work.
You need to to json_decode($content, true); to obtain an array and not an object.
See http://php.net/manual/fr/function.json-decode.php
Also the array_push is not correctly called.
It should be : array_push($tempArray, ["userid"=>$userId,"accesstoken" => $accessToken]);
You have error in json file so that all suggesion not working remove , at end of array. Then try below code :
Your json file should be:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
}
]
php :
$content = file_get_contents('user.json');
$tempArray = json_decode($content,true);
$new_array = array("userId"=>$userId,"accesstoken"=>$accessToken);
array_push($tempArray, $new_array);
$jsonData = json_encode($tempArray);
file_put_contents('user.json', $jsonData);

API Data Return to HTML

I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.

Automatically loop API Json response

I'm attempting to insert all results from a JSON API result, they have put a limit on max 200 results per page, although they provide the next url to be accessed to get the next 200 results, here's an example of the result that the API provides.
{
"count": 200,
"total": 31108,
"nextUrl": "https://**/api/v1/***/orders?secure_auth_key=****&offset=200",
"orders": [
{
"number": 40026,
"paymentStatus": "ACCEPTED",
etc....
}
],
}
Here is my current code to grab these 200 results and store them in mySQL
$url = "https://****/api/v1/***/orders?secure_auth_key=*****";
$json = file_get_contents($url, 0, null, null);
$result = json_decode($json, true)
foreach($result['orders'] as $order) {
mysql_query("INSERT INTO blah blah");
}
How can i create it so it automatically gets the data from the next page e.g : offset=200 and add all the data to database like i did in the first results.
With the assumption that if there is no more results they don't provide a URL for the next 200, why not just use that as a check.
eg. after your save simple if to check if the last result had a nexturl?
if(isset($result['nextUrl'])){
$url = $result['nextUrl'];
$json = file_get_contents($url, 0, null, null);
$result = json_decode($json, true)
foreach($result['orders'] as $order) {
mysql_query("INSERT INTO blah blah");
}
}
Ideally move that into a function you can continually call where needed...

Parsing JSON object in PHP using json_decode

I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.

Categories