It’s all about generating JSON
Let’s examine a couple of ways to create JSON-encoded data with PHP. For my examples, I will assume that I need to send to the browser the data needed to populate a combo box that will display a list of categories.
This is the definition of my ExtJS combo box:
The categoriesStore data store is a JsonStore that points to a PHP page where I will create the categories data:
As defined in the store, the data will need to have a form similar to this:
The above is just a JSON representation of an object containing a categories array. Each array element is an object that represents a category, which in turn has two properties: id, and name. Our categories.php page will need to produce this data and send it to the browser.
Hand-crafting a JSON representation of an object
The first approach I will show you consists of hand-crafting the JSON representation of the categories object. Although PHP has facilities for creating JSON-encoded data, I recommend you try this approach as a way to get familiar with the JSON structures. This is how the PHP page would look like:
In a more realistic scenario the categories information could have been obtained through a database call. Let’s assume I will use MySQL as the database and change the page like so:
Here I just transformed the query results into a JSON-encoded string in the form that my ExtJS ComboBox needs.
The second approach I want to show you uses a PHP facility for JSON-encoding strings.
Using PHP’s JSON manipulation functions
Json_encode($value) is a function that returns a string containing the JSON representation of a value. In the code below I create and populate a two-dimensional array that contains the categories information, which I then pass to the json_encode function.
As you might have expected, using json_encode considerably simplifies creating JSON data. I encourage you to read its documentation to gain full understanding of its capabilities and limitations.