Broadcast on Broadcast off
The Documentation for Project Zero has moved. Please update your bookmarks to: http://www.projectzero.org/documentation/
Table of
Contents...
Hide
 

JSON handling in PHP

JavaScript Object Notation (JSON) is a simple data format that is commonly used to transfer data to JavaScript client code. More information about JSON can be found at the JSON Web site json.org.

There are several ways to handle JSON-formatted data in PHP.

API

From PHP scripts, you can manipulate JSON directly using the following API functions.

json_encode
json_decode

The following example illustrates how to parse JSON data that has been sent in the POST body in to PHP variables.

<?php

// The raw post body is available in the variable $HTTP_RAW_POST_DATA
$employee = json_decode($HTTP_RAW_POST_DATA);

$sql = "SELECT * FROM employees WHERE employeeid = ".$employee['id'];

?>

The same using PHP streams.

<?php
$input = fopen("php://input", 'r');

// The raw post body is available in the variable $HTTP_RAW_POST_DATA
$employee = json_decode(fread($input, 999));

$sql = "SELECT * FROM employees WHERE employeeid = ".$employee['id'];

?>

The example code below will render the following output.

<?php

$indexedArray = array(
"a", "b", "c"
);

$result = json_encode($indexedArray);
echo "Indexed array = " . $result . "<br/>";

$keyedArray = array(
1 => "a", 
2 => "b", 
3 => "c"
);

$result = json_encode($keyedArray);
echo "Keyed array = " . $result . "<br/>";	

?>

Output from example.

Indexed array = [ "a", "b", "c" ]
Keyed array = { "1": "a", "2": "b", "3": "c" }

Response handling

As described in the Response rendering section of the Core Developer's Guide, it is possible to use the global context to render a request response as JSON. The example below is followed by the resulting output.

<?php
$customer = array('name' => 'John Smith');

zput('/request/view', 'JSON');
zput('/request/json/output', $customer);
render_view();
?>

Output from example.

{"name":"John Smith"}

JSONResultHandler for data access

The zero.data.php dependency provides a sample ResultHandler that is written in PHP. It is implemented in the JSONResultHandler.php file and automatically included in the PHP include path whenever you have zero.data.php as a dependency. This handler takes the result of a query operation, which is a JDBC ResultSet, and renders it as JSON. Specifically, this is an array of maps with column names as keys. See the PHP data access article in the Core Developer's Guide for details.

r6 - 08 Nov 2007 - 20:02:18 - madhu
Syndicate this site RSS ATOM
Copyright 2007 © IBM Corporation | Privacy | Terms of Use | About this site