今天使用POST方式(GET方式也要注意)向PHP提交了一個(gè)JSON數(shù)據(jù),比如:
{"a":1,"b":2}
在PHP中取出這個(gè)數(shù)據(jù):$s=$_POST['data'] ;//or $_GET['data'],然后這個(gè)串取出后是被轉(zhuǎn)義的:{"a":1,"b":2}
如果直接調(diào)用:
- $obj = json_decode($s);
- print_r($obj);
- echo $obj->a;
是錯(cuò)誤的,會(huì)報(bào)告錯(cuò)誤.如果$s直接定義:$s='{"a":1,"b":2}';則沒有問題.所以在PHP中處理JSON時(shí)需要進(jìn)行一下轉(zhuǎn)義處理:$s=strips教程lashes($_POST['data']) ;這樣再進(jìn)行json解碼就可以了.
json_decode — 對(duì) JSON 格式的字符串進(jìn)行編碼
json_encode — 對(duì)變量進(jìn)行 JSON 編碼
Report a bug 說明
string json_encode ( mixed $value )
返回 value 值的 JSON 形式
Report a bug 參數(shù)
value
待編碼的 value,除了resource 類型之外,可以為任何數(shù)據(jù)類型,該函數(shù)只能接受 UTF-8 編碼的數(shù)據(jù)(譯注:指字符/字符串類型的數(shù)據(jù))
Report a bug 返回值
編碼成功則返回一個(gè)以 JSON 形式表示的 string 。
Report a bug 范例
Example #1 A json_encode() 的例子,代碼如下:
- <?php
- $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
- echo json_encode($arr);
- ?>
- //以上例程會(huì)輸出:
- {"a":1,"b":2,"c":3,"d":4,"e":5}
json_encode — 對(duì)變量進(jìn)行 JSON 編碼
json_decode — 對(duì) JSON 格式的字符串進(jìn)行編碼
Report a bug 說明
mixed json_decode ( string $json [, bool $assoc ] )
接受一個(gè) JSON 格式的字符串并且把它轉(zhuǎn)換為 PHP 變量
Report a bug 參數(shù)
json
待解碼的 json string 格式的字符串。
assoc
當(dāng)該參數(shù)為 TRUE 時(shí),將返回 array 而非 object 。
Report a bug 返回值
Report a bug 范例
Example #1 json_decode() 的例子
- <?php
- $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
- var_dump(json_decode($json));
- var_dump(json_decode($json, true));
- ?>
- /*
- 以上例程會(huì)輸出:
- object(stdClass)#1 (5) {
- ["a"] => int(1)
- ["b"] => int(2)
- ["c"] => int(3)
- ["d"] => int(4)
- ["e"] => int(5)
- }
- array(5) {
- ["a"] => int(1)
- ["b"] => int(2)
- ["c"] => int(3)
- ["d"] => int(4)
- ["e"] => int(5)
- }
- */
新聞熱點(diǎn)
疑難解答