I want to return JSON from a PHP script.
Do I just echo the result? Do I have to set the Content-Type
header?
|
While you're usually fine without it, you can and should set the Content-Type header:
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). |
|||||||||||||||||||||
|
A complete piece of nice and clear PHP code returning JSON is:
|
|||||||||||||||||||||
|
Try json_encode to encode the data and set the content-type with |
|||
|
According to the manual on
When this happens
This error condition should be captured in PHP, for example like this:
Then the receiving end should of course be aware that the presence of the jsonError property indicates an error condition, which it should treat accordingly. In production mode it might be better to send only a generic error status to the client and log the more specific error messages for later investigation. Read more about dealing with JSON errors in Documention |
|||||||||||||
|
Set the content type with |
|||
|
The answer to your question is here, It says.
so if you set the header to that type, and output your JSON string, it should work. |
|||
|
You can use this little PHP library. It sends the headers and give you an object to use it easily. It looks like :
|
||||
|
Yeah, you'll need to use echo to display output. Mimetype: application/json |
|||
|
If you need to get json from php sending custom information you can add this |
|||
|
As said above:
will make the job. but keep in mind that :
|
|||
|