views:

46

answers:

5

I want to return a .JSON from a PHP script, do I just echo the result? Do I have to set header content-types?

Any help would be great!

A: 

Set the content type with header('Content-type: application/json'); and then echo your data.

bemace
A: 

The answer to your question is here,

It says.

The MIME media type for JSON text is application/json.

so if you set the header to that type, and output your JSON string, it should work.

Codemwnci
A: 

Yeah, you'll need to use echo to display output. Mimetype: application/json

Nev Stokes
+1  A: 

Try json_encode to encode the data and set the content-type with header('Content-type: application/json');.

thejh
+3  A: 

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

<?PHP
$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).

timdev