Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON object in PHP using json_decode

Tags:

json

php

People also ask

What is the use of json_decode in PHP?

The json_decode() function is used to decode or convert a JSON object to a PHP object.

How can access JSON decoded data in PHP?

PHP - Accessing the Decoded Values$obj = json_decode($jsonobj);

How is JSON parse in PHP?

Parsing JSON with PHPPHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.

What is json_decode File_get_contents PHP input?

file_get_contents() function: This function in PHP is used to read a file into a string. json_decode() function: This function takes a JSON string and converts it into a PHP variable that may be an array or an object.


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.