
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.
ARRAY
var_dump can be used to output the array.
var_dump($parsed_json);
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.
Hello
Did you find this article helpful?
If so, consider buying me a coffee over at