FreeKB - PHP Getting Started with json_decode
PHP - Getting Started with json_decode

The json_decode function can be used to parse json. For example, let's say you have the following JSON.

 "foo": "Hello",
 "bar": "World"


In this example, the JSON is stored in a variable named $json.

$json = '{"foo":"Hello","bar":"World"}';


Or, if the JSON is in a file, you would do the following to store the JSON in a variable named $json.

$json = file_get_contents('example.json');


Echoing the variable . . .

echo $json;


... will return the raw json.

{ "foo": "Hello", "bar": "World" }


You will want to store the parsed json in a new variable. By default, json_decode will create JSON as a variable.

$parsed_json = json_decode($json);


Or "true" can be used to create JSON as an array.

$parsed_json = json_decode($json, true);


Attempting to echo the variable . . .

echo $parsed_json;


... with print ARRAY.



var_dump can be used to output the array.



var_dump should produce something like this. 

array(2) { ["foo"]=> string(5) "Hello" ["bar"]=> string(5) "World" }


This output shows that the 'foo' key contains a value of 'Hello' and the 'bar' key contains a value of 'World'. Here is how to echo the value of the 'foo' key.

echo $parsed_json['foo'];


Which should output.




Add a Comment

We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.

Please enter f4c61 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |