Skip to main content

skip to main content

developerWorks  >  Open source  >

What's new in PHP V5.2, Part 3: Using the new JSON extension

Learn how to make PHP and Ajax shake hands

developerWorks
Document options

Document options requiring JavaScript are not displayed


My developerWorks needs you!

Connect to your technical community


Rate this page

Help us improve this content


Level: Intermediate

Tracy Peterson (tracy@tracypeterson.com), Freelance Writer, Consultant

27 Mar 2007

PHP continues to evolve and incorporate useful standards as they are created and adopted among Internet application developers. PHP just added a JavaScript Object Notation (JSON) extension to PHP V5.2, which was previously only available as add-on framework classes. This addition provides PHP developers with better support for Ajax applications using JSON. This article, Part 3 of a five-part "What's new in PHP V5.2" series, shows how to use this application effectively, and after completing this article, you will be proficient at using the built-in JSON extensions with PHP for your Ajax applications.

Enter Ajax

Ajax is picking up speed all over the Internet as a great way to create fully functional Web applications that break the rules and limitations of the Web browser by separating data form and function through the power of XML. A major limitation of Ajax involves handling XML in JavaScript. The things that make XML great make it complex to handle as well. After you have ensured that an XML document is formatted correctly and you have set up your error handling, you still have to put the XML into some kind of usable object for JavaScript. Getting XML into your application for use is not as easy as it sounds.

Since XML is not native to JavaScript, we are much better off using a language to which XML is native, such as PHP and use the simple data, converted to a format native to JavaScript.

Another issue we run into is that we don't always want or need to convert data to XML before we ship it off to our Ajax application. We do have standards to meet, however, before our Ajax developers can use the data we provide. Once we have created an object in our PHP code, we can serialize it, export it to the Ajax portion of the application, manipulate it, and bring it on back.



Back to top


JSON

JSON is a protocol designed to allow middleware to create objects formatted in a JavaScript native format. Its most powerful attribute is that it is a lightweight protocol. When you are simply processing an RSS aggregation or a list of recipes, you don't need the full power of XML in JavaScript. There is no need to validate the format or to ensure strict data typing. We can skip a great deal of the workload associated with handling XML, even though the term Ajax includes XML. For the sake of writing more concise code, you can use JSON to simplify the process. Let's look at an example of a simple XML document showing data from an RSS feed database application.


Listing 1. XML format example

Listing 1 - XML Format Example
<?xml version="1.0" ?>
<root>
     <feed>
          <id>21</id>
<url>www.blah.com/story1.html</url>
     <title>JSON is sweeping AJAX world</title>
     <viewed>FALSE</viewed>
</feed>
<feed >
     <id>22</id>
<url> www.blah.com/story2.html</url>
     <title>JSON is great</title>
     <viewed>FALSE</viewed>
</feed>
</root>

To get this XML document, we would have accessed our database, pulled out the relevant data, and used PHP to format it in this XML document. Although Ajax can utilize XML, in many cases, it is overkill. The amount of overhead bandwidth needed for the control structures is simply not needed for an application as simple as sharing some links. In addition, we have to work through our MySQL results recursively, removing illegal characters and building our XML document bit by bit.

JSON helps in this case, as we can serialize any PHP object using json_encode() to turn that object into a JSON protocol string, ready for an Ajax application to read. This is much more convenient than creating an XML document, as we simply have to feed our MySQL results directly to the function. Since our MySQL results come in the form of an associative array, there is no intermediary step.

Let's have a look at what would happen if we converted the above XML document into a JSON object (see Listing 2). For the moment, the database and data formats are arbitrary; we will get into what they actually look like in a later section.


Listing 2. Example of PHP to convert XML to JSON

<?php
//we assume that $results is the result of an SQL query but we will construct it now
$results = array("21" => array("url" => "www.blah.com/story1.html", 
"title" => "JSON is sweeping AJAX world", 
"viewed" => FALSE), "22" => array("url" => "www.blah.com/story2.html", 
"title" => "JSON is great", "viewed" => FALSE));
//we now have a populated array object in $results resembling a possible MySQL result

$jsonObject = json_encode($results);
echo $jsonObject;
?>

Did you catch all that? No recursing through the results. No adding tags. Just put it through the json_encode() function, and it comes out the other side as a JSON serialized object. See Listing 3 for a look at our new object.


Listing 3. Example of JSON serialized XML object

{"21":{"url":"www.blah.com\/story1.html","title":"JSON is sweeping AJAX 
world","viewed":false},"22":{"url":"www.blah.com\/story2.html",
"title":"JSON is great","viewed":false}}

We have a string that contains our array object, serialized in JSON format. A couple important things to note about this string are that the encode function has automatically escaped our forward slashes with backslashes, and our variable types are identifiable depending on if we have quotes. Since the ID numbers in the array were quoted, those are recognized as strings. The Boolean false elements are maintained as Booleans.

Now that we have serialized our object, we can use it in any number of JSON functions in an Ajax application.



Back to top


Encoding and decoding

There are two functions for JSON: encode and decode. The first, as you would imagine, converts a data object of any kind into a serialized set of data, ready for JavaScript to handle. The second decodes the serialized data and converts it to a basic PHP object or an associative array. We have already seen an example of using json_encode(), so let's take a look at json_decode().


Listing 4. An example of json_decode()

<?php
$jsonObject = '{"21":{"url":"www.blah.com\/story1.html","title":"JSON is sweeping AJAX 
world","viewed":false},"22":{"url":"www.blah.com\/story2.html","title":"JSON is 
great","viewed":false}}';

$decodedObject = json_decode($jsonObject);
$decodedArray = json_decode($jsonObject, true);

print_r($decodedObject);
echo "<br><br>";
print_r($decodedArray);

?>

Above, we have a PHP script that takes our $jsonObject and decodes it back to a PHP native object. We decode twice. First, we use the unmodified usage, which would result in an object of stdClass, and the second time, we use the Boolean argument to create an associative array.


Listing 5. Output from Listing 4

stdClass Object ( [21] => stdClass Object ( [url] => www.blah.com/story1.html [title] => 
JSON is sweeping AJAX world [viewed] => ) [22] => stdClass Object ( [url] => 
www.blah.com/story2.html [title] => JSON is great [viewed] => ) )
 
Array ( [21] => Array ( [url] => www.blah.com/story1.html 
[title] => JSON is sweeping AJAX world [viewed] => ) 
[22] => Array ( [url] => www.blah.com/story2.html [title] => 
JSON is great [viewed] => ) )

We see the two objects, listed out using print_r().



Back to top


From database to JSON

In the proposed Ajax application, our program manager wants to use data from a database which another application provides. An RSS aggregator, which stores results from selected RSS feeds in our MySQL database on our Web server, is constantly checking and updating RSS. To read them, our application calls for an Ajax interface. As dedicated back-end programmers, we will focus on getting the data from the database all the way to JSON format. We will leave the Ajax to the experts, but we will certainly get it ready for them to handle.

First, we will set up our MySQL database to store our RSS feed information, then insert a couple of records to start us off. We will then write a PHP script that goes into our database and retrieves some records for our JSON-enabled application to use.



Back to top


Setting up

We need to set up our MySQL database and insert some simple records for us to pull out. For the sake of these examples, we will use the database name "RSS_AGG" (see Listing 6). PHP is incredibly flexible when it comes to database selection, with most major Relational Database Management Systems (RDBMS) supported natively. Some are not, but many of these are even supported through abstraction classes or extensions. I used MySQL, but feel free to adapt this code to support a database of your choice.


Listing 6. SQL for feeds table and two records

CREATE TABLE 'feeds' (
  'id' int(11) NOT NULL auto_increment,
  'url' text NOT NULL,
  'title' text NOT NULL,
  'viewed' tinyint(1) NOT NULL,
  PRIMARY KEY  ('id')
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO 'feeds' ('id', 'url', 'title', 'viewed') VALUES 
(1, 'www.blah.com/story1.html', 'JSON is sweeping AJAX world', 0),
(2, 'www.blah.com/story2.html', 'JSON is great', 0);

We now have a database we can access through our PHP scripts. As with all database interaction, we need to set up our database connections and get our data out.


Listing 7. output.php

<?php

$username="username";
$password="password";
$database="rss_agg";
$sql="SELECT * FROM `feeds`";

mysql_connect(localhost, $username, $password);
mysql_select_db($database) or die("Unable to select database");
$result = mysql_query($sql);

mysql_close();
?>

In this start of our output script, we simply create variables to store our username and password for access to the database located at localhost. We selected our database, named rss_agg and wrote a very simple SELECT statement to retrieve all records from the feeds table. The next three lines use our connection credentials to initiate a connection to the database, and we then select the database. If this can't happen for any reason, we would see the result "Unable to select database." Finally, we retrieve the results of our SQL statement and close the connection to the database.



Back to top


Encoding to JSON

Before we can convert our MySQL result to a JSON string, we need to convert it to a usable PHP object. We can do that by turning it into an array.


Listing 8. output.php with JSON code

<?php
$username="root";
$password="";
$database="rss_agg";
$sql="SELECT * FROM `feeds`";
$encodable = array();

mysql_connect(localhost, $username, $password);
mysql_select_db($database) or die("Unable to select database");
$result = mysql_query($sql);

while($obj = mysql_fetch_object($result))
{
$encodable[] = $obj;
}

$encoded = json_encode($encodable);

echo $encoded;

mysql_close();
?>

We have created an array object to store our results information in a format that json_encode() could read and convert to a JSON string. The while statement steps through each element of the result query and builds the $encodable array line by line. Once this object is complete, we simply run it through json_encode() and produce the $encoded object. We can now echo this information to the browser, feeding the requesting JavaScript with the data from our object. The requesting JavaScript application now has an exact copy of our PHP object, enumerated in a way that is natively understandable by JavaScript.



Back to top


Summary

JSON is a useful, lightweight protocol, now available in PHP V5.2, which makes the process of getting data out of our PHP applications and into our Ajax applications an easy one. Appropriately, JSON in PHP is just as lightweight and useful, only having two functions that are simple to use. Using these functions, we can convert and export our object structures and make data from our PHP database connections available to our Ajax applications using json_encode(). Once we have manipulated the data in the Ajax applications, we can bring the data back into our PHP scripts and recreate the usable object data structures with json_decode(). Once we have the data back into PHP, we can store it in our database or any other method of data handling we choose from the many options PHP offers.



Resources

Learn

Get products and technologies
  • Innovate your next open source development project with IBM trial software, available for download or on DVD.


Discuss


About the author

Tracy Peterson has worked as an IT project manager and Web developer since 1997 and most recently worked as an operations program manager on MSN Search at Microsoft. He is based in San Francisco.




Rate this page


Please take a moment to complete this form to help us better serve you.



 


 


Not
useful
Extremely
useful
 


Share this....

digg Digg this story del.icio.us del.icio.us Slashdot Slashdot it!



Back to top