Converting PHP to JSONP with json_encode

PHP has a nice function called json_encode that will transform a PHP array into a JSON object. This is very useful for converting data and publishing it for use with AJAX requests.

When you want your data to be accessible from a different domain you must take your JSON and turn it into a callback function in order to let the data be read inside the browser. The easiest way to do this is by reading the callback value from the get and putting it around the JSON output.

<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
$json = json_encode($arr);
$callback = $_GET[callback];
echo $callback . '(' . $json . ')';
?>

If you do this you’ll have no problems interacting with jQuery’s getJSON function and you’ll be publishing your data in a very portable format.

This entry was posted in Code, General and tagged , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>