jsonwrapper: json_encode for earlier versions of PHP 5.x

What is this about?

PHP 5.2 adds the json_encode function, which turns almost any PHP data structure into valid JavaScript code. Hashes, arrays, arrays of hashes, whatever.

Unfortunately a lot of Linux distributions are still shipping with PHP 5.1.x.

jsonwrapper implements the json_encode function if it is missing, and leaves it alone if it is already present. So it is nicely future-compatible.

Just add:

require 'jsonwrapper.php';

At the top of your code and you're ready to go. Of course, jsonwrapper.php must be in the same folder. If not, adjust the require command.

json_encode example

Just to give you a sense of the possibilities:

$data = array(
array('name' => 'Jane', 'age' => 35),
array('name' => 'Steve', 'age' => 37)
);
<script>
var data = <?php echo json_encode($data) ?>;
</script>

Boom, your array is now available to your JavaScript code.

How To Get It

Click here for a gzipped tarfile.

Credits and License Terms

jsonwrapper itself is hereby released into the public domain. However, it is a simple wrapper around M. Migurski's PEAR JSON library, which has its own free license. You could also install that from PEAR and change my wrapper to use the copy you pulled down from PEAR. See the tarfile for details.

Follow us on Twitter | Contact Us

Copyright 1994-2014 Boutell.Com, Inc. All Rights Reserved.