How to output JSON using PHP
PHP (version 5 >= 5.2.0, PECL json >= 1.2.0) provides a method json_encode to convert array to string.
$sample = array( 'name'=>'My Name', 'email'=>'my_email@example.com' ); echo json_encode($sample);
The above code will output JSON string, but please NOTE that it is not ready to be considered as JSON. We need to set content type using http headers before printing the JSON string.
header('Content-Type: application/json'); echo json_encode($sample);
8 Responses to How to output JSON using PHP
Leave a Reply Cancel reply

Tags
Ad ADT Adword AJAX Android API balancing Binding Calling Class Column Configure Copy Curl Data Database Eclipse Error Gadget Google Hello ini ini_set Install Invite Javascript Late Linux Load Master Method MySQL Output PHP Playground Proxy Replication SeaMonkey Server Slave Static String Table Ubuntu upload_max_filesize






Umm, the content type should really be: application/json not text/javascript.
There is a also a nice little plugin for firefox (JSON View) which will pretty print the JSON.
Recommended one is application/json but text/javascript is widely used, well known companies are using test/javascript for json. Both are understandable by the browser by the way. You can easily view it in firebug, almost all developers have it.
agree to admin, my opinion :
text/javascript is better – there was a bug in some Firefox versions:
I saw the following (FF):
php with “application/json” was not interpreted.
The user was asked to download it an downloaded a 0k file.
“text/javascript” worked here. Use “text/javascript”.
Using
text/javascriptinstead of the appropriate header to go-round browser bugs is not a good idea. You should look forward, rather than drag behind bugs.JSON – JavaScript Object Notation… Nuff said.
I am having a little problem when I echo it. The json is showing in an unreadable format, I installed JSONView and it doesn’t work. Can you help me?
Chrome and Safari development tools are quite useful. Try switching your browser.
I was looking through some of your content on this website and I conceive this site is real informative! Continue posting.