I want to return clean JSON from a PHP header script after page load. 

Do I have to set the Content-Type header or just echo result?

php json header 

Nov 17

4 Answers

Its quite easy to return clean JSON from a PHP header script after page load. 

You just need to add header script to your page or URL 'Content-Type: application/json'.


header('Content-Type: application/json');
$colors = array("VOLVO","BMW","BENZ");
echo json_encode($colors);

answered Dec 02

Header JSON and the returned response


By adding a header with content type as JSON:

 $result = array('menu1' => 'home', 'menu2' => 'code php', 'menu3' => 'about');

//return the json response :
header('Content-Type: application/json');  // <-- header declaration
echo json_encode($result, true);    // <--- encode

The header is there so your app can detect what data was returned and how it should handle it.
Note that: the content header is just information about the type of returned data.

If you are using UTF-8, you can use :

header("Content-Type: application/json;charset=utf-8");

Example jQuery :

        console.table('json ',data);
        console.log('Menu1 : ', data.menu1);

answered Dec 30

While you're usually fine without it, you can and should set the Content-Type header:

$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);

If I'm not using a particular framework, I usually allow some request params to modify the output behavior. It can be useful, generally for quick troubleshooting, to not send a header, or sometimes print_r the data payload to eyeball it (though in most cases, it shouldn't be necessary).

answered Dec 30

Try this out.

function loadlink(){
    $('#links').load('test.php',function () {

loadlink(); // This will run on page load
    loadlink() // this will run after every 5 seconds
}, 5000);

Hope this helps.

answered Dec 30

Login and Submit Your Answer
Browse other questions tagged  php  json  header or ask your own question.