Actions

Difference between revisions of "Generating JSON output"

From Joomla! Documentation

m (added to advanced)
(2 intermediate revisions by 2 users not shown)
Line 14: Line 14:
 
<?php
 
<?php
 
// Set up the data to be sent in the response.
 
// Set up the data to be sent in the response.
$data = array( 'some data' );
+
$data = array('some data');
  
 
// Get the document object.
 
// Get the document object.
Line 20: Line 20:
  
 
// Set the MIME type for JSON output.
 
// Set the MIME type for JSON output.
$document->setMimeEncoding( 'application/json' );
+
$document->setMimeEncoding('application/json');
  
 
// Change the suggested filename.
 
// Change the suggested filename.
JResponse::setHeader( 'Content-Disposition', 'attachment; filename="'.$view->getName().'.json"' );
+
JResponse::setHeader('Content-Disposition','attachment;filename="'.$view->getName().'.json"');
  
 
// Output the JSON data.
 
// Output the JSON data.
echo json_encode( $data );
+
echo json_encode($data);
 
</source>
 
</source>
<noinclude>[[Category:Development]]</noinclude>
+
<noinclude>[[Category:Development]][[Category:Tutorials]][[Category:Advanced]]</noinclude>
[[Category:Tips and tricks]][[Category:Module Development]]
+
[[Category:Plugin Development]]
+
[[Category:Component Development]]
+

Revision as of 07:06, 13 September 2012

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