Actions

Difference between revisions of "Generating JSON output"

From Joomla! Documentation

m (Adjusted category)
Line 28: Line 28:
 
echo json_encode( $data );
 
echo json_encode( $data );
 
</source>
 
</source>
<noinclude>[[Category:Development]]</noinclude>
+
<noinclude>[[Category:Development]][[Category:Tutorials]]</noinclude>
[[Category:Tips and tricks]][[Category:Module Development]]
+
[[Category:Plugin Development]]
+
[[Category:Component Development]]
+

Revision as of 13:42, 2 February 2011

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

<?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 );