Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1

(^248) CHAPTER 16 ■ ADVANCED ZEND FRAMEWORK


Password:







To access your login form, visit [http://example.com/index/login.](http://example.com/index/login.)

Using JSON with PHP


The Zend_Json class provides a simple encoder/decoder mechanism to convert variables
between JSON and PHP. This component is fairly self-explanatory and is demonstrated in the
context of a JSON action in Listing 16-12.

Listing 16-12. Using Zend_Json

public function jsonAction() {
$this->getHelper('ViewRenderer')->setNoRender();

//Simulate a JSON input value
$jsonInput = '[0,1,2,3]';

//Decode JSON to a PHP array
$phpArray = Zend_Json::decode($jsonInput);

//Do a PHP operation
shuffle($phpArray);

//Encode the data for output
$jsonOutput = Zend_Json::encode($phpArray);

//Get the response object and set content type HTTP header
$response = $this->getResponse();
$response->setHeader('Content-Type', 'application/json');

//Make sure the JSON is the only output data
$response->clearBody();
//Set the response body to the JSON code
$response->setBody($jsonOutput);
}

Normal operation of a JSON decode in PHP is to turn JSON objects into associative arrays.
Since this is not always desirable, the Zend Framework provides an alternative decode syntax;

$phpObject = Zend_Json::decode('{"x":1}', Zend_Json::TYPE_OBJECT);

McArthur_819-9C16.fm Page 248 Friday, February 29, 2008 5:07 PM

Free download pdf