Creating JSON Data in PHP

by Shea Frederick on March 10th, 2007

So you need to encode JSON data for use with ExtJS or some other library? If you are lucky enough to be running PHP 5.2.0 or greater, then you have the optimal environment for encoding JSON data. But all is not lost if you dont have this setup, there are plenty of librarys you can use to take care of this task.

For our examples we are using a MySQL database as the data source.

PHP 5.2.0 or higher

As of PHP 5.2.0, the JSON extension is bundled and compiled into PHP by default, which makes life for you extremely easy. This is also a highly optimized implementation of JSON for PHP, so if you have this available to you, then use it.

Eleven lines of code and you have data ready to be used by many of the Ext objects.

Less than PHP 5.2.0 and no root access

The PEAR JSON package will be the way to go if you cant use PHP 5.2.0 or greater and you do not have root access to install php extensions. There are other libraries available, but this librarys inclusion in PEAR makes it the clear choice for reliability.

http://pear.php.net/pepr/pepr-proposal-show.php?id=198

Just two more lines of code to include the library, create an instance of the JSON service, and change the call to encode (line 14).

Less than PHP 5.2.0 with root access

For those of you that need to keep your current version of PHP but want the speed gained by using the PHP JSON extension can download and install it yourself, granted you have root access to the box your on.

http://www.aurore.net/projects/php-json/

This way you can use the native PHP JSON functions, so the example code for PHP 5.2.0 or higher will work.

From PHP

2 Comments
  1. Hey there, I am trying the examples in the ebook and I have not been able to get the Ch. 3 forms_load_data.php to work. In fact, I have never been able to get a form directly loaded upon window display. I can only get a grid to load.

    I found a thread in the ExtJS forum that discussed stripping the square brackets from the start/end JSON string that is generated in php json_encode. Is this required? Thanks for your response!

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS