Diety Dieticheskie-produkty Protsedury Sredstva Uprajneniya Fitnes Gimnastika Yoga Pitanie Tsellyulit Zdorove Krasota

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);
Tagged with:

11 Responses to How to output JSON using PHP

  1. a_musing_moose says:

    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. admin says:

    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. Sebastian Lasse says:

    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. Gajus says:

    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. Nicholas says:

    JSON – JavaScript Object Notation… Nuff said.

  6. jgauna says:

    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?

  7. admin says:

    Chrome and Safari development tools are quite useful. Try switching your browser.

  8. matth says:

    i have problem echo json

  9. I was looking through some of your content on this website and I conceive this site is real informative! Continue posting.

  10. Manny says:

    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?

  11. bhuvana says:

    thanks it works

Leave a Reply

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