Generating JSON output
(New page: PHP has native functions to encode and decode JSON data. You can encode data using the json_encode function, like this: <source lang="php"> <?php // Set up the dat...)
|Line 29:||Line 29:|
Revision as of 15:48, 29 September 2010
<?php // Set up the data to be sent in the response. $data = array( 'some data' ); // Output the JSON data. echo json_encode( $data );
The json_encode function can encode almost all data types, such as strings, arrays and objects, although you may need to be aware that the corresponding json_decode function will only return an object (or optionally, an associative array).
It is good practice to set the MIME-type for the output correctly. In some applications you might also want to change the suggested filename to something other than the "index.php" that you will probably get by default. In the following example the suggested filename is changed to the name of the view, with a ".json" extension added.
<?php // Set up the data to be sent in the response. $data = array( 'some data' ); // Get the document object. $document =& JFactory::getDocument(); // Set the MIME type for JSON output. $document->setMimeEncoding( 'application/json' ); // Change the suggested filename. JResponse::setHeader( 'Content-Disposition', 'attachment; filename="'.$view->getName().'.json"' ); // Output the JSON data. echo json_encode( $data );