Get data from JSON file with PHP [duplicate] - php

This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 4 years ago.
I'm trying to get data from the following JSON file using PHP. I specifically want "temperatureMin" and "temperatureMax".
It's probably really simple, but I have no idea how to do this. I'm stuck on what to do after file_get_contents("file.json"). Some help would be greatly appreciated!
{
"daily": {
"summary": "No precipitation for the week; temperatures rising to 6° on Tuesday.",
"icon": "clear-day",
"data": [
{
"time": 1383458400,
"summary": "Mostly cloudy throughout the day.",
"icon": "partly-cloudy-day",
"sunriseTime": 1383491266,
"sunsetTime": 1383523844,
"temperatureMin": -3.46,
"temperatureMinTime": 1383544800,
"temperatureMax": -1.12,
"temperatureMaxTime": 1383458400,
}
]
}
}

Get the content of the JSON file using file_get_contents():
$str = file_get_contents('http://example.com/example.json/');
Now decode the JSON using json_decode():
$json = json_decode($str, true); // decode the JSON into an associative array
You have an associative array containing all the information. To figure out how to access the values you need, you can do the following:
echo '<pre>' . print_r($json, true) . '</pre>';
This will print out the contents of the array in a nice readable format. Note that the second parameter is set to true in order to let print_r() know that the output should be returned (rather than just printed to screen). Then, you access the elements you want, like so:
$temperatureMin = $json['daily']['data'][0]['temperatureMin'];
$temperatureMax = $json['daily']['data'][0]['temperatureMax'];
Or loop through the array however you wish:
foreach ($json['daily']['data'] as $field => $value) {
// Use $field and $value here
}
Demo!

Use json_decode to transform your JSON into a PHP array. Example:
$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

Try:
$data = file_get_contents ("file.json");
$json = json_decode($data, true);
foreach ($json as $key => $value) {
if (!is_array($value)) {
echo $key . '=>' . $value . '<br/>';
} else {
foreach ($value as $key => $val) {
echo $key . '=>' . $val . '<br/>';
}
}
}

Related

looping over all elements in JSON response PHP

After making a cURL call, I get a JSON response back as follows, already decoded as a string.
{
"AAPL": {
"fundamental": {
"symbol": "AAPL",
"high52": 229.67,
"low52": 149.16,
}
}
If I want to loop over all elements in 'fundamental,' what would be the best loop to use for this in PHP? I have tried the foreach method, but I was getting an illegal character use message.
I also get the error:
Undefined property: stdClass::$fundamental when trying:
$json_new = json_decode($json);
echo $json_new->fundamental;
The current foreach:
foreach ($json_new as $val){
echo $val->fundamental;
}
Step-1: decode JSON to array
$arr = json_decode($json, true);
Step-2: loop
foreach ($arr['AAPL']['fundamental'] as $key => $val) {
echo $key . ' = ' . $val . PHP_EOL;
}

Print JSON keys of an array within another array in PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I have the following JSON code:
{
"google.com": {
"clicks": 23,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
},
"mcnitro.net": {
"clicks": 87,
"browsers": {
"Chrome": 19,
"Mozilla": 2,
"Safari": 1
}
}
}
And I am endeavouring to print on the document page the arrays' names and their children.
So far, I have tried the following PHP code:
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data->children() as $domain) {
echo $data[$domain];
foreach($data[$domain] as $value) {
echo $value['clicks'];
}
}
?>
However, I am facing an issue in the error_log:
PHP Fatal error: Call to a member function children() on array in /home/gamin167/public_html/ads/engine/300x250/gen.js.php on line 5
The result wanted was to have "google.com" and "mcnitro.net" printed, as well as their "clicks" property.
Any tip or advice will be highly appreciated! Thanks in advance!
You decode the string to an array with true yet you seem to try and use it as an object.
Also there is no need to loop twice.
foreach($data as $key => $domain) {
echo $key . "\n";
echo $domain['clicks'] . "\n\n";
}
output:
google.com
23
mcnitro.net
87
https://3v4l.org/D7FCY
You cannot use ->children(). $data is an array with your json data, and you can use foreach to get key and value, like foreach ($data as $key => $value).
So here, to get your domain name, just do :
<?php
header("Content-type: text/javascript");
$jsonString = file_get_contents('stats.json');
$data = json_decode($jsonString, true);
foreach($data as $domain => $value) {
echo $value['clicks'];
}
?>

(PHP, JSON) Foreach [duplicate]

This question already has answers here:
How can I combine two strings together in PHP?
(19 answers)
Closed 4 months ago.
I have a question about php and json. Im running this php in foreach loop. But when i get all the tank_id from the json file. I get results like
8011819314145
I want it to display like:
Tank ID: 801
Tank ID: 18193
Tank ID: 14145
What i'm doing wrong? Help me thank you.
Here is my php file:
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo $tank_id['tank_id'];
}
?>
In a foreach you can get both the key and the value. Take a look at the following pseudo-code
foreach ($array as $key => $value) {
echo $key.': '.$value.'<br />';
}
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
echo('<pre>');
//print_r($json_tank);
foreach ($json_tank['data']['521997295'] as $tank_id) {
echo "Tank ID: " . $tank_id['tank_id'] . '<br/>';
}
You just need to format output as you want.
<?php
$json = file_get_contents("https://api.worldoftanks.eu/wot/account/tanks/?application_id=demo&account_id=521997295");
$json_tank = json_decode($json, TRUE);
foreach ($json_tank['521997295'] as $tank_id) {
echo 'Tank ID: '.$tank_id['tank_id'].' ';
}
?>

Issues with decoding json object

Thanks for your time in reading this post.
My php file is receiving a json object. But I am facing issues while decoding it.
My php code:
$data=$_POST['arg1'];
echo $data;
$json = json_decode($data,true);
echo $json;
$i = 1;
foreach($json as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
$i++;
}
When I echo data results as below.
{
"SCI-2": {
"quantity": 2,
"id": "SCI-2",
"price": 280,
"cid": "ARTCOTSB"
}
}
When I echo $json, result is as it follows :
Array
Name1 : Array.
Please assist as i need tho access the cid and quantity values in the $data.
json_decode returns an array. And to print array you can use print_r or var_dump.
Now to access your values you can try :
$json["SCI-2"]["quantity"] for quantity and $json["SCI-2"]["cid"] for cid.
Demo : https://eval.in/522350
To access in foreach you need this :
foreach($json as $k) {
foreach($k as $key => $value) {
print "<h3>Name".$i." : " . $value . "</h3>";
}
}
Since you do not know the number of items in your object, use this:
$obj = json_decode($json);
After this, iterate the $obj variable and after that, inside the loop, use the foreach to get each property.
foreach($iteratedObject as $key => $value) {
//your stuff
}

How to get values of a json array in php?

I have json like this:
{
"Products": [
{
"_id": 1
....
},
{
"_id": 2
....
}
]
}
And got this json :
$str = file_get_contents($_FILES["uploadFile"]["tmp_name"]);
// convert object => json
$json = json_encode($str);
// convert json => object
$decoded = json_decode($json,true);
Now i want to see all _id of Producs.
I use this echo $decoded[0]['_id']; but it shows nothing.
Any ideas?
$decoded = json_decode($json, true);
echo $decoded['products'][0]['_id'];
This decodes the json as an array that you can use just like any other array in PHP, if you have trouble accessing values, then simply do a print_r($decoded) and that should show you its structure
If you want to loop over all the ids, then simply do a foreach loop
foreach($decoded as $inner_array) {
foreach($inner_array as $products) {
echo $products['_id'];
}
}
Working demo
You should be aware of using quotes on your json string :)
keys and values .
You don't need to encode it. the string is already in json format
$str= '{"Products": [{"_id": "1"},{"_id": "2"}]}';
$decoded = json_decode($str,true);
echo $decoded['Products'][0]['_id'];

Categories