Actions

Difference between revisions of "Generating JSON output"

From Joomla! Documentation

m (Adjusted category)
m (wikipedia link)
 
(2 intermediate revisions by 2 users not shown)
Line 1: Line 1:
PHP has native functions to encode and decode [[JSON]] data.  You can encode data using the [[php:json_encode|json_encode]] function, like this:
+
PHP has native functions to encode and decode [[wp:JSON|JSON]] data.  You can encode data using the [[php:json_encode|json_encode]] function, like this:
 
<source lang="php">
 
<source lang="php">
 
<?php
 
<?php
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]][[Category:Tutorials]]</noinclude>
+
<noinclude>[[Category:Development]][[Category:Tutorials]][[Category:Advanced]]</noinclude>

Latest revision as of 16:10, 19 June 2013

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