Using JSON with PHP
May 9, 2008 — techxplorerIn a recent programming task I’ve been working on I’ve needed to transfer some data, in the form of arrays, from one PHP page to another via hidden input fields in a form. I’ve used JSON for this task. More information on JSON is available at the official website.
Some of things I’ve learnt are:
Check to ensure the JSON functions are available
The JSON functions in PHP are provided by an extension that is only bundled with PHP version 5.2 and above. If you don’t have that specific version you can compile and include the php-json extension yourself, or use the JSON-PHP library which is written in pure PHP and doesn’t require any compilation.
Detecting which library to use is easy
To ensure your code doesn’t cause problems you can construct it in such a way that it detects if the php-json extension is available and if not use the json-php library using code like this:
if(!function_exists('json_encode')) {
// PHP pre 5.2 or the library isn't installed
// include the alternate library
require_once('path/to/library/JSON.php');
$json_services = new Services_JSON();
$encoded = $json_services->encode($my_var);
} else {
$encoded = json_encode($my_var);
}
The same technique will work for decoding as well:
if(!function_exists('json_encode')) {
// PHP pre 5.2 or the library isn't installed
// include the alternate library
require_once('path/to/library/JSON.php');
$json_services = new Services_JSON();
$my_var = $json_services->decode($encoded);
} else {
$my_var = json_decode($encoded);
}
Including the data in a form requires some extra work
To include the data in the form, you need to change the double quotes (”) in the encoded data into single quotes (’). Otherwise the generated HTML will be invalid. You can do this quite easily using the str_replace function. Remember to do the reverse replacement before decoding the data.
Ensure you get the variable type you expect
By default an array will be decoded as an object. This can make using it in your code a little bit more complicated. Fortunately the json_decode function will take an additional boolean operator to return an array, and you can use variable type casting when using the json-php library. For example:
if(!function_exists('json_encode')) {
// PHP pre 5.2 or the library isn't installed
// include the alternate library
require_once('path/to/library/JSON.php');
$json_services = new Services_JSON();
$my_array = (array) $json_services->decode($encoded);
} else {
$my_array = json_decode($encoded, TRUE);
}
I’ve been using the 
I had an issue with a 









