How to output JSON using PHP

PHP Logo

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

11 thoughts on “How to output JSON using PHP”

  1. 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.

  2. 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.

  3. 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”.

  4. 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.

  5. 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?

  6. 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?

Leave a Reply

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