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(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.

Answer from BMBM on Stack Overflow
๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ php โ€บ ozcpn0mv โ€บ php-parse-json-example
How do I parse JSON string in PHP?
If the JSON cannot be parsed or ... encoded strings. To encode PHP objects to JSON string, you can use json_encode($value) function. In this PHP JSON Parse example, we use the json_decode() function to decode JSON strings into PHP objects....
๐ŸŒ
PHP
php.net โ€บ manual โ€บ en โ€บ function.json-decode.php
PHP: json_decode - Manual
If you want to enforce an array to encode to a JSON list (all array keys will be discarded), use: json_encode(array_values($array)); If you want to enforce an array to encode to a JSON object, use: json_encode((object)$array); See also: ...
๐ŸŒ
Envato Tuts+
code.tutsplus.com โ€บ home โ€บ cloud & hosting
How to Parse JSON in PHP | Envato Tuts+
May 31, 2021 - This tutorial will teach you how to read a JSON file and convert it to an array in PHP. Learn how to parse JSON using the json_decode() and json_encode() functions.
๐ŸŒ
PHPpot
phppot.com โ€บ php โ€บ json-handling-with-php-how-to-encode-write-parse-decode-and-convert
JSON Handling with PHP: How to Encode, Write, Parse, Decode and Convert - PHPpot
A comprehensive guide for JSON handling with PHP that includes example code to read, write, parse, encode, decode and convert JSON data.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ php โ€บ how-to-parse-a-json-file-in-php
How to parse a JSON File in PHP? - GeeksforGeeks
Note: The second argument (true) ensures that the JSON data is returned as an associative array. Without it, the data is returned as an object. Here is the complete PHP code that reads, the JSON file, then decodesoutputs it and output the result:
Published ย  June 24, 2025
๐ŸŒ
Tutorial Republic
tutorialrepublic.com โ€บ php-tutorial โ€บ php-json-parsing.php
How to Encode and Decode JSON Data in PHP - Tutorial Republic
In this tutorial you will learn how to encode and decode JSON data in PHP. JSON stands for JavaScript Object Notation. JSON is a standard lightweight data-interchange format which is quick and easy to parse and generate.
๐ŸŒ
W3Docs
w3docs.com โ€บ php
How to Create and Parse JSON Data with PHP
"<br>"; } echo "<hr>"; // Decode JSON data to PHP object $obj = json_decode($json); // Loop through the object foreach ($obj as $key => $value) { echo $key . "=>" . $value . "<br>"; } ?> ... JSON or the JavaScript Object Notation is a ...
Find elsewhere
๐ŸŒ
CodeSignal
codesignal.com โ€บ learn โ€บ courses โ€บ handling-json-files-with-php โ€บ lessons โ€บ parsing-and-accessing-json-data-with-php
Parsing and Accessing JSON Data with PHP
Decode the data using json_decode() to convert it into a PHP associative array. ... To access specific data from the parsed JSON, such as the school name, you navigate the hierarchical structure using keys: In this example, $data['school'] is used to locate the value associated with school ...
๐ŸŒ
W3Schools
w3schools.com โ€บ php โ€บ php_json.asp
PHP and JSON
PHP has some built-in functions to handle JSON. First, we will look at the following two functions: ... The json_encode() function is used to encode a value to JSON format. This example shows how to encode an associative array into a JSON object:
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_json_php.asp
JSON PHP
Here is a JavaScript on the client, using an AJAX call to request the PHP file from the array example above: Use JSON.parse() to convert the result into a JavaScript array:
Top answer
1 of 3
107

If your $result variable is a string json like, you must use json_decode function to parse it as an object or array:

$result = '{"Cancelled":false,"MessageID":"402f481b-c420-481f-b129-7b2d8ce7cf0a","Queued":false,"SMSError":2,"SMSIncomingMessages":null,"Sent":false,"SentDateTime":"\/Date(-62135578800000-0500)\/"}';
$json = json_decode($result, true);
print_r($json);

OUTPUT

Array
(
    [Cancelled] => 
    [MessageID] => 402f481b-c420-481f-b129-7b2d8ce7cf0a
    [Queued] => 
    [SMSError] => 2
    [SMSIncomingMessages] => 
    [Sent] => 
    [SentDateTime] => /Date(-62135578800000-0500)/
)

Now you can work with $json variable as an array:

echo $json['MessageID'];
echo $json['SMSError'];
// other stuff

References:

  • json_decode - PHP Manual
2 of 3
13

The main problem with your example code is that the $result variable you use to store the output of curl_exec() does not contain the body of the HTTP response - it contains the value true. If you try to print_r() that, it will just say "1".

The curl_exec() reference explains:

Return Values

Returns TRUE on success or FALSE on failure. However, if the CURLOPT_RETURNTRANSFER option is set, it will return the result on success, FALSE on failure.

So if you want to get the HTTP response body in your $result variable, you must first run

curl_setopt($cURL, CURLOPT_RETURNTRANSFER, true);

After that, you can call json_decode() on $result, as other answers have noted.

On a general note - the curl library for PHP is useful and has a lot of features to handle the minutia of HTTP protocol (and others), but if all you want is to GET some resource or even POST to some URL, and read the response - then file_get_contents() is all you'll ever need: it is much simpler to use and have much less surprising behavior to worry about.

๐ŸŒ
GitHub
github.com โ€บ halaxa โ€บ json-machine
GitHub - halaxa/json-machine: Efficient, easy-to-use, and fast PHP JSON stream parser ยท GitHub
Syntax errors in the structure of a json stream between the iterated items will still throw SyntaxError exception though. ... JSON Machine reads a stream (or a file) 1 JSON item at a time and generates corresponding 1 PHP item at a time.
Author ย  halaxa
๐ŸŒ
Temboo
temboo.com โ€บ php โ€บ parsing-json
Parsing JSON in PHP
Select PHP from the drop down menu at the top of the page.. 2 Enter any search term you want for the Query input and click Generate Code to test the Choreo from our website. 3 You get a whole bunch of JSON in the Response output. These are the results of the search. Next we'll see how to parse through this response in PHP and pick out only the pieces we're interested in.
๐ŸŒ
Nidup
nidup.io โ€บ blog โ€บ manipulate-json-files-in-php
Read, Decode, Encode, Write JSON in PHP | Nicolas Dupont
March 12, 2022 - In this tutorial, we will learn how to perform the most common manipulation, such as encoding, decoding, and converting JSON to Array and Array to JSON with the help of examples. We'll also discover how to read and write JSON files in PHP.
Top answer
1 of 3
610

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

  • scalars: strings, ints, floats, and bools
  • nulls (a special type of its own)
  • compound types: objects and arrays.

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:

  • Processing large JSON files in PHP
  • How to properly iterate through a big json file

How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

2 of 3
5
<?php
$jsonData = '{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

// Decode the JSON
$data = json_decode($jsonData, true);

// Access the data
$type = $data['type'];
$name = $data['name'];
$toppings = $data['toppings'];

// Access individual topping details
$firstTopping = $toppings[0];
$firstToppingId = $firstTopping['id'];
$firstToppingType = $firstTopping['type'];

// Print the data
echo "Type: $type\n";
echo "Name: $name\n";
echo "First Topping ID: $firstToppingId\n";
echo "First Topping Type: $firstToppingType\n";
?>

In this example, json_decode() is used to decode the JSON data into a PHP associative array. You can then access the individual elements of the array as you would with any PHP array.

๐ŸŒ
ReqBin
reqbin.com โ€บ code โ€บ php โ€บ zg4d50d8 โ€บ php-json-decode-example
How do I decode JSON in PHP?
To encode PHP objects to JSON, you can use the json_encode($value) function. In this PHP Decode JSON example, we use the json_decode() function to convert a JSON string into a PHP object using default values.
๐ŸŒ
Reintech
reintech.io โ€บ blog โ€บ php-json-encoding-decoding-web-services
PHP and JSON: Encoding, Decoding, and Web Services | Reintech media
April 28, 2023 - Here's a complete example integrating all concepts into a RESTful API endpoint: // api/users.php header('Content-Type: application/json; charset=utf-8'); try { // Parse request $method = $_SERVER['REQUEST_METHOD']; $input = file_get_content...
๐ŸŒ
ZetCode
zetcode.com โ€บ php โ€บ json
PHP JSON - working with JSON in PHP
It is easily read and written by humans and parsed and generated by machines. The application/json is the official Internet media type for JSON. The JSON filename extension is .json. The json_encode function returns the JSON representation of the given value. The json_decode takes a JSON encoded string and converts it into a PHP variable. PHP frameworks such as Symfony and Laravel have built-in methods that work with JSON. In the following example, we use the json_encode function.