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!

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

  5. oops, sorry, forgot to do the [code][/code] thing

    Hi, I am stumped on producing a specifically formatted JSON for a flot chart. Any help is much appreciated!

    I use this php code

    [code]
    $query = mysql_query(‘SELECT * FROM all_programs_extended’);

    while($row = mysql_fetch_assoc($query)) {
    $newData[] = array(
    ‘label’ => $row[‘program_type’],
    ‘data’ => array(
    “employee1” => $row[’employee1′],
    “employee2” => $row[’employee2′],
    “employee3” => $row[’employee3′]
    )
    );

    }

    print json_encode($newData);

    [/code]
    which produces this valid JSON

    [{“label”:”Program A”,”data”:{“employee1″:”5″,”employee2″:”3″,”employee3″:”1”,}},
    {“label”:”Program B”,”data”:{“employee1″:”0″,”employee2″:”4″,”employee3″:”2”,}},
    {“label”:”Program A”,”data”:{“employee1″:”4″,”employee2″:”2″,”employee3″:”4”,}}]

    but I need it look like this:

    {
    “label”: “Program A”,
    “data”: [[employee1, 5], [employee2, 3], [employee3, 1]],
    “label”: “Program B”,
    “data”: [[employee1, 0], [employee2, 4], [employee3, 2]],
    “label”: “Program C”,
    “data”: [[employee1, 4], [employee2, 2], [employee3, 4]]

    }

    I seem to have mixed up by brackets and braces, and I also need a comma separating my value pairs between brackets rather than the colon in the first JSON. Be nice to get ride of the quotation marks around the numbers too!

    Thanks very much!

    • For the data elements, try wrapping them in another level of array, so where you have “employee2” => $row[’employee2′] wrap an array() around the whole thing.

      I think that should get you closer to what you need.

  6. Hey, great post. I have a quick question… So far my php code produces an array of elements in json format:
    PHP code (snippet):
    [code]
    $sql = “select * from customercarpark”;
    $result = mysqli_query($con, $sql) or die(“Error in Selecting ” . mysqli_error($con));
    $emparray = array();
    while($row = mysqli_fetch_assoc($result))
    {
    $emparray[] = $row;
    }
    echo json_encode($emparray);
    [/code]

    This gives me the output:
    [{“StudentID”:”13000000″,”TagNumber”:”111111111″,”FirstName”:”Megan”,”LastName”:”Smith”,”ContactNumber”:”07135274827″},{“StudentID”:”13011111″,”TagNumber”:”212355852″,”FirstName”:”John”,”LastName”:”Smith”,”ContactNumber”:”07523244423″}]

    How would I alter the php code so that this array will have a name/label so the output will be like this:
    { “Customers” : [ {“StudentID”:”13000000″,”TagNumber”:”111111111″,”FirstName”:”Megan”,”LastName”:”Smith”,”ContactNumber”:”07135274827″},{“StudentID”:”13011111″,”TagNumber”:”212355852″,”FirstName”:”John”,”LastName”:”Smith”,”ContactNumber”:”07523244423″}] }

    I’m sure it’s pretty simple but I’ve been searching for ages and cannot find anything, any help would be great :) thanks

    • The JSON output depends on how your array is structured – so you can change the line inside the while loop to say

      $emparray[“Customers”][] = $row;

      Then each individual record will go into a new element inside the Customers index in the array, and when you json_encode() it, you’ll get the structure you mentioned. Hope that makes sense …

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.