Moving data around in JSON format is an increasingly important developer skill. PHP offers two useful methods for both distributing data in the JSON format but also receiving data in JSON format.

json_encode() - PHP Array to JSON

The json_encode() method will take a PHP array and encode it as JSON ready to be consumed by an AJAX call.

$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike');
$myJson = json_encode($myarray);
echo $myJson;

View The Demo.

json_decode() - JSON to PHP Array

Working the other way around, json_decode() will take JSON and convert it into a PHP array.

$myJson = '{"Guitar" : "Johnny", "Vocals": "Stephen", "Bass" : "Andy", "Drums" : "Mike"}';
$myarray = json_decode($myJson, true);
print_r($myarray);

Notice that json_decode() takes a second parameter true indicating we would like an associate array returned. Also notice that the JSON name / value pairs are placed in double quotes.

View The Demo.

serialize() and unserialize()

Similiar to json_encode() and json_decode() are serialize() and unserialize(). The serialize() method will 'serialize' the likes of a PHP array. By serialize we mean it will take the complex data structure of an array and convert it to basic text string that could be then stored in a database. This basic text string is something unique to PHP but it does look very similar to JSON. If you receive data in a PHP serialized format from a database, or indeed from an API, then to get in back into a manipulable array format you use unserialize().

For example:

$myarray = array('Guitar' => 'Johnny', 'Vocals'=> 'Stephen', 'Bass' => 'Andy', 'Drums' => 'Mike');
$mySerial = serialize($myarray);
echo $mySerial;

View The Demo.

Leave a Comment