本文實(shí)例講述了PHP的JSON封裝、轉(zhuǎn)變及輸出操作。分享給大家供大家參考,具體如下:
Json封裝
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
protected function renderJSON( $data =[], $msg = "ok" , $code = 200) { //設(shè)置格式 header( 'Content-type: application/json' ); //輸出json格式的內(nèi)容 print_r(json_encode([ "code" => $code , "msg" => $msg , "data" => $data , "req_id" => uniqid() ])); //結(jié)束 return Yii:: $app -> end (); } |
Json轉(zhuǎn)變
1
2
3
4
5
6
7
8
9
10
11
12
13
|
<?php // 告訴瀏覽器以json編碼 header( 'Content-type:text/json' ); $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}' ; // 沒有設(shè)置則輸出對象 var_dump(json_decode( $json )); echo "<br>" ; // 為true則為輸出數(shù)組 var_dump(json_decode( $json , true)); echo "<br>" ; $array = array ( 'a' , 'f' , 'q' , 'd' , 'a' , 'g' ); var_dump(json_encode( $array ,JSON_HEX_TAG)); ?> |
Json輸出
1
2
3
4
5
6
|
<?php // 告訴瀏覽器以json編碼 header( 'Content-type:text/json' ); $json = '{"fruit":{{"apple":"蘋果"},{"banana":"蘋果"}}' ; // string(49) "{"fruit":{{"apple":"蘋果"},{"banana":"蘋果"}}" var_dump( $json ); |
希望本文所述對大家PHP程序設(shè)計(jì)有所幫助。
原文鏈接:https://blog.csdn.net/fujian9544/article/details/89413801