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);
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/javascript
instead 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 have problem echo json
I was looking through some of your content on this website and I conceive this site is real informative! Continue posting.
How to solve chrome issues, it is echoing $data in browser instead passing to $.ajax({…. post code, it is working in other browser except chrome?
thanks it works