标签云

微信群

扫码加入我们

WeChat QR Code

I want to return JSON from a PHP script.

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


Can you show us what you have tried?

2018年07月17日06分31秒

just in case: you should use header() commands only in addition with output buffering to avoid "headers already sent" warnings

2018年07月18日06分31秒

The php file have to be encoded in UTF-8 without BOM :)

2018年07月17日06分31秒

header('Content-type:application/json;charset=utf-8');

2018年07月17日06分31秒

mikepote I actually don't think it's necessary to have the header command at the top of the PHP file. If you're inadvertently spitting out stuff and that's tripping up your header command, you just need to fix your code because it's broken.

2018年07月17日06分31秒

KrzysztofKalinowski no, the PHP file doesn't need to be UTF-8 encoded. the output MUST be UTF-8 encoded. Those wrong statements doesn't help non-experienced users to learn how to avoid things from breaking, but it helps to grow myths on them and never learning which role does encodings play on streams and how they work.

2018年07月18日06分31秒

More parsimoniously, if ( $option == 1 ){ $data = $data1; } else { $data = $data2; } header('Content-type: application/json'); echo json_encode( $data ); Having the conditional AFTER the header statement is unnecessary and ugly.

2018年07月17日06分31秒

There's no charset parameter for JSON; see the note at the end of tools.ietf.org/html/rfc8259#section-11: "No 'charset' parameter is defined for this registration. Adding one really has no effect on compliant recipients." (JSON must be transmitted as UTF-8 per tools.ietf.org/html/rfc8259#section-8.1, so specifying that it's encoded as UTF-8 is a bit redundant.)

2018年07月18日06分31秒

Thanks for highlighting that, PatrickDark. Redundant charset parameter removed from HTTP header string.

2018年07月17日06分31秒