PHP and JSON

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!

9 thoughts on “PHP and JSON

  1. I donĀ“t have alternatives or addition but I wanted to thank you for this.
    I read it and implemented it yesterday and I should say that I was impressed! Thank you for the tip!
    I also cannot wait for the phpbnl11 to start! It will be great, I am sure!
    See you there hopefully!

  2. I see json_decode() to be pretty useless without setting it's second parameter to true to obtain an associative array.

    What can you do with an stdClass object? Iterate over it? get_class_vars() returns an associative array of what could be built directly by json_decode($str, true).

    A stdClass object simply is not really useful, and json_decode() has no way to define using another class like mysqli_fetch_object().

    • I almost never use json_decode() without true as the second argument either--I find stdClass objects generally pretty useless.

      json_encode()'s JSON_FORCE_OBJECT in 5.3 is useful in dealing with PHP's array/hash duality:

      json_encode(array())
      // -> "[]"
      json_encode(array(), JSON_FORCE_OBJECT)
      // -> "{}"

      • thanks everyone who mentioned about the object/array flag. Since I was only passing it to print_r it didn't occur to me to switch it!

        Michael: I didn't know 5.3 was getting that new functionality, thanks for adding your comment :)

  3. Thank you very much, I am very new to PHP Web services. Your article about PHP and JSON simply superb. Now I understand to write my own code.

  4. What if I had something like

    {
    "results": [
    "time_of_day":{
    "lunch": xxxxx,
    "dinner": yyyyyy,
    }
    }

    How would I use php to extract the value for lunch and dinner?

    • Your sample isn't valid JSON so PHP won't decode it, but essentially you do json_decode() and pass in the value like you posted there, and I recommend you pass "TRUE" as the second parameter so that you get an array.

      Call print_r() on the array to see what's in it, then you can do something like $array['results']['time_of_day']['lunch'] - depending on the structure of your (valid) JSON.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>