Json php


*

*

While you"re usually fine without it, you can & should phối the Content-Type header:

If I"m not using a particular framework, I usually allow some request params lớn modify the output behavior. It can be useful, generally for quichồng troubleshooting, khổng lồ not send a header, or sometimes print_r the data payload khổng lồ eyeball it (though in most cases, it shouldn"t be necessary).

Bạn đang xem: Json php


*

*

A complete piece of nice & clear PHPhường code returning JSON is:

$option = $_GET<"option">;if ( $option == 1 ) $data = < "a", "b", "c" >; // will encode to JSON array: <"a","b","c"> // accessed as example in JavaScript like: result<1> (returns "b") else $data = < "name" => "God", "age" => -1 >; // will encode to lớn JSON object: "name":"God","age":-1 // accessed as example in JavaScript like: result.name or result<"name"> (returns "God")header("Content-type: application/json");eđến json_encode( $data );
Share
Improve sầu this answer
Follow
edited Oct 26 "16 at 13:37

*

Áxel Costas Pemãng cầu
4,80455 gold badges2626 silver badges5353 bronze badges
answered Jul 31 "14 at 15:26
aesedeaesede
5,04722 gold badges3232 silver badges3232 bronze badges
0
Add a bình luận |
53
According khổng lồ the manual on json_encode the method can return a non-string (false):

Returns a JSON encoded string on success or FALSE on failure.

Xem thêm: Html Là Viết Tắt Của Một Trang Web, Nền Tảng Lập Trình Web Cho Người Mới Bắt Đầu

When this happens emang đến json_encode($data) will output the empty string, which is invalid JSON.

Xem thêm: Bột Gelatin Mua Ở Đâu Tại Tphcm, Cách Sử Dụng Bột Gelatin

json_encode will for instance fail (& return false) if its argument contains a non UTF-8 string.

This error condition should be captured in PHPhường., for example like this:

json_last_error_msg()>); if ($json === false) // This should not happen, but we go all the way now: $json = ""jsonError":"unknown""; // Set HTTPhường response status code to: 500 - Internal Server Error http_response_code(500);}emang lại $json;?>Then the receiving over 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 lớn skết thúc only a generic error status to the client và log the more specific error messages for later investigation.


Chuyên mục: