What's he up to?
Serve JSON correctly using PHP
From Kees van den Broek. June 30, 2009, 4 Comments
When prototyping, it’s handy to use a plain text file that contains JSON instead of generating its content by code.
But consuming JSON data from JavaScript works better when it’s served using the appointed application/json mimetype.
Using the PHP wrapper below, that plain text file is served correctly.
By providing the optional jsonp parameter, the JSON can also returned as JSONP.
The script may also be used as a proxy to get JSON data from another domain to prevent crossdomain scripting errors.
<?php $url = $_REQUEST['url']; if ($url) { $data = file_get_contents($url); } else { echo "Please provide the 'url' parameter."; return; } $jsonp = $_REQUEST['jsonp']; if ($jsonp) { $data = $jsonp . "(" . $data . ");"; header('Content-type: text/javascript'); } else { header('Content-type: application/json'); } echo $data; ?>
Usage examples:
When the above script is saved as jsonwrapper.php and put on yourhost.com, use it like:
http://yourhost.com/jsonwrapper.php?url=http://anyurl.com/some_json.txt
And, optionally, to wrap the JSON in a function call as JSONP:
http://yourhost.com/jsonwrapper.php?url=http://anyurl.com/some_json.txt&jsonp=mycallback
Using mimetype application/json combined with JSONP is incorrect. Mimetype application/json should be parsed by a JSON-parser, JSONP by a JavaScript-parser. So JSONP has to be served with mime-type text/javascript and JSON with mime-type application/json.
By the way, the name of the mime-type is also not consistent. Why do we use text/javascript, text/html, text/xml, text/… but we use application for JSON..
You’re right. Script updated.
Thanks!
By the way, text/xml is deprecated and application/xml should be used instead. See e.g.
http://www.grauw.nl/blog/entry/489
http://annevankesteren.nl/2004/08/mime-types
Actually I was not correct: it seems that text/xml is not deprecated (yet?) by any standard. But text/javascript is obsolete (by IANA), and application/javascript should be used instead:
http://www.iana.org/assignments/media-types/text/
http://tools.ietf.org/html/rfc4329#section-7.1