DerekAllard.com

Using JSON on servers without native support

If you’re building a distributed application one of the luxuries you lack is knowing exactly how the server that will be hosting your application is configured. One common obstacle I encounter is lack of JSON support (JSON is only natively available to PHP since version 5 version 5.2, and even then is not uniformly available on servers). Here’s how I code around this situation; firstly, if the server does support JSON, then I don’t want to mess with it, but if it lacks support for JSON, then we need to define the JSON functions so it can use them externally. There are 2 JSON functions that we want to re-create - json_decode(), and json_encode().

Often times these types of things are set using configuration variables (in CodeIgniter, the $config array), but a configuration variable in this case is not really desirable, as a server may get the ability afterwards, or the person implementing it may not set the variable correctly. What I do in order to ensure the system will guess correctly is simply use PHP’s native function_exists() function to determine if the server can handle JSON. If it cannot, then I re-implement all the functions using the PEAR Json_services file, which I implement as a CodeIgniter library.

// Not all servers will have json_decode() available but those that do should
// use it, and we'll fall back to another solution for those who don't. 
if ( ! function_exists('json_decode'))
{
    $this
->load->library('Services_json');

The library is available from the Pear repository and will work in any environment that CodeIgniter itself works in, simply drop it into your libraries folder.

function codeigniter_controller ()
{
    
if ( ! function_exists('json_decode'))
    
{
        $this
->load->library('Services_json');
    
}

    $json 
'{"a":1,"b":2,"c":3,"d":4,"e":5}';

    
$vars['json'json_decode($json);

    
$this->load->view('view'$vars);

I’ve used this technique successfully now across several CodeIgniter projects.