This tutorial shows you how to use PHP to return a JSON object to a client.
DOWNLOAD THE SOURCE CODE
JSON has become a preferred format for transferring data across the internet. It has the benefit of being valid JavaScript code, making it trivial to use the format withing JavaScript applications. And because of it's popularity a lot of other languages support converting objects to and from JSON.
This tutorial will show you how to make a very simple PHP web service that returns a JSON object.
This application will return a JSON object with the current time of the server. A recent change in PHP 5 is that date and time functions will return a warning if the default time zone has not been set. This is done with the date_default_timezone_set function.
date_default_timezone_set('Australia/Adelaide');
For this demo we will send back a very simple class, which includes a string and the date. The PHP code the defines this class is shown below.
class TimeInfo
{
public $testString = "This is a test PHP object";
public $currentTime = null;
function __construct()
{
$this->currentTime = date_create();
}
}
Here we create a new instance of the TimeInfo class, and use the native PHP json_encode function to serialize the PHP object into a JSON string.
$ti = new TimeInfo();
$jsonString = json_encode($ti);
Because we are returning a JSON string, and not HTML, we need to set some HTTP headers to let the client know that it is recieveing JSON code.
There is a useful Wikipedia page that shows you the mime types for various types of files. JSON has a content type of application/json.
header('Content-type: application/json');
header("Content-Disposition: inline; filename=TimeInfo.json");
And then finally we send the JSON code that was created in step 3.
echo $jsonString;
You can test the any JSON string in a handy Online JSON Parser, which will notify you of any syntax errors, and display a nicely formatted tree view of the JSON object if the code is valid.
With the built in json_decode and json_encode PHP functions, using PHP as either the source or end consumer of JSON objects is a very simple task.
Return to the Tutorial Index

Creating PDF documents with PHP
This tutorial steps you through the process of creating PDF documents with PHP.