Serializing and deserializing JSON with PHP

JSON (JavaScript Object Notation) is a standard for interchanging data. You might want to use for serializing and deserializing form input.

Browser and Server interchange JSON

This example uses the built-in functions of PHP5 for serializing and deserializing a multidimensional array.

<?php

    // Construct the array containing users
    $users = array();

    $users[] = array('name' => 'Joe', 'occupation' => 'Student');
    $users[] = array('name' => 'Bob', 'occupation' => 'Miner');
    $users[] = array('name' => 'Betty', 'occupation' => 'Housewife');

    // Serialize and print the JSON data
    $serializedUsers = json_encode($users);

    print "Serialized: ".$serializedUsers."\n";

    // Deserialize and print the array
    $deserializedUsers = json_decode($serializedUsers);

    print "Deserialized: ".var_export($deserializedUsers,true)."\n";

?>

Output:

Serialized: [{"name":"Joe","occupation":"Student"},{"name":"Bob","occupation":"Miner"},{"name":"Betty","occupation":"Housewife"}]
Deserialized: array (
  0 =>
  stdClass::__set_state(array(
     'name' => 'Joe',
     'occupation' => 'Student',
  )),
  1 =>
  stdClass::__set_state(array(
     'name' => 'Bob',
     'occupation' => 'Miner',
  )),
  2 =>
  stdClass::__set_state(array(
     'name' => 'Betty',
     'occupation' => 'Housewife',
  )),
)
This entry was posted in PHP and tagged , , , , , , , , , , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

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>

Why ask?