Generating JSON output

From Joomla! Documentation

Revision as of 06:06, 13 September 2012 by Tom Hutchison (Talk | contribs)

PHP has native functions to encode and decode JSON data. You can encode data using the json_encode function, like this:

// 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.

// 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.
// Change the suggested filename.
// Output the JSON data.
echo json_encode($data);