PHP 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: text/javascript');
echo json_encode($sample);
Tagged with:
 

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

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">