This is a quick outline on working with JSON from PHP, which is actually pretty simple to do. This post has some examples on how to do it and what the results should look like. JSON stands for JavaScript Object Notation, and is widely used in many languages (not just JavaScript) for serialisation. It is particularly popular for use in web services.
Writing JSON From PHP
Imagine we have a multidimensional array in PHP that looks something like this:
$menu['starter'] = array( "prawn cocktail",
"soup of the day");
$menu['main course'] = array( "roast chicken",
"fish 'n' chips",
"macaroni cheese");
$menu['pudding'] = array( "cheesecake",
"treacle sponge");
echo json_encode($menu);
The output of this script looks like this:
{"starter":["prawn cocktail","soup of the day"],"main course":["roast chicken","fish 'n' chips","macaroni cheese"],"pudding":["cheesecake","treacle sponge"]}
This is pretty typical of a JSON output string – you can see the curly brackets to enclose the whole thing, then some square brackets to show the nesting levels within the key/value formats. JSON is an ideal format for many applications because it is easy to understand and debug, its quite concise, and many languages have built-in support just like PHP.
Reading JSON Data From PHP
Once we’ve serialised the string, we might want to unserialise it again – and the PHP code for that is every bit as simple as the previous example, except that we use the function json_decode() instead of json_encode(). I’ve set the output of the previous script as the input to this one:
$json = '{"starter":["prawn cocktail","soup of the day"],"main course":["roast chicken","fish \'n\' chips","macaroni cheese"],"pudding":["cheesecake","treacle sponge"]}';
print_r(json_decode($json));
This decodes the string and then dumps it using print_r() – the output of my script looked like this:
stdClass Object
(
[starter] => Array
(
[0] => prawn cocktail
[1] => soup of the day
)
[main course] => Array
(
[0] => roast chicken
[1] => fish 'n' chips
[2] => macaroni cheese
)
[pudding] => Array
(
[0] => cheesecake
[1] => treacle sponge
)
)
Note that the data isn’t identical to how it looked when it went in – JSON can’t distinguish between arrays and objects, and doesn’t retain information about data types. So its perfect for a web service where we just want to convey the information, but may be too loose for other applications.
The examples here were taken from a talk I give about consuming web services – you can see all the slides on slideshare. If you have any additions or alternatives, leave a comment!