摘要:今天使用POST方式(GET方式也要注意)向PHP提交了一個JSON數(shù)據(jù),比如:{"a":1,"b":2}在PHP中取出這個數(shù)據(jù):$s=$_POST[& 39;data& 39;] ; or $_GET[& 39;data& 39;],然后這個串...
轉(zhuǎn)載請注明來源:php json函數(shù)用法

今天使用POST方式(GET方式也要注意)向PHP提交了一個JSON數(shù)據(jù),比如:

{"a":1,"b":2}

在PHP中取出這個數(shù)據(jù):$s=$_POST['data'] ;//or $_GET['data'],然后這個串取出后是被轉(zhuǎn)義的:{"a":1,"b":2}

如果直接調(diào)用:

  1. $obj = json_decode($s);  
  2. print_r($obj);   
  3. echo $obj->a; 

是錯誤的,會報告錯誤.如果$s直接定義:$s='{"a":1,"b":2}';則沒有問題.所以在PHP中處理JSON時需要進(jìn)行一下轉(zhuǎn)義處理:$s=strips

json_decode — 對 JSON 格式的字符串進(jìn)行編碼

json_encode — 對變量進(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 返回值

編碼成功則返回一個以 JSON 形式表示的 string 。

Report a bug 范例

Example #1 A json_encode() 的例子,代碼如下:

  1. <?php 
  2. $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
  3.  
  4. echo json_encode($arr); 
  5. ?>  
  6. //以上例程會輸出: 
  7. {"a":1,"b":2,"c":3,"d":4,"e":5} 

json_encode — 對變量進(jìn)行 JSON 編碼

json_decode — 對 JSON 格式的字符串進(jìn)行編碼

Report a bug 說明

mixed json_decode ( string $json [, bool $assoc ] )

接受一個 JSON 格式的字符串并且把它轉(zhuǎn)換為 PHP 變量

Report a bug 參數(shù)

json 

待解碼的 json string 格式的字符串。

assoc 

當(dāng)該參數(shù)為 TRUE 時,將返回 array 而非 object 。

Report a bug 返回值

Returns an object or if the optional assoc parameter is TRUE, an associative array is instead returned.

Report a bug 范例

Example #1 json_decode() 的例子

  1. <?php 
  2. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
  3.  
  4. var_dump(json_decode($json)); 
  5. var_dump(json_decode($json, true)); 
  6.  
  7. ?>  
  8. /* 
  9. 以上例程會輸出: 
  10. object(stdClass)#1 (5) { 
  11.     ["a"] => int(1) 
  12.     ["b"] => int(2) 
  13.     ["c"] => int(3) 
  14.     ["d"] => int(4) 
  15.     ["e"] => int(5) 
  16. } 
  17.  
  18. array(5) { 
  19.     ["a"] => int(1) 
  20.     ["b"] => int(2) 
  21.     ["c"] => int(3) 
  22.     ["d"] => int(4) 
  23.     ["e"] => int(5) 
  24. } 
  25. */ 
轉(zhuǎn)載請注明來源:
php json函數(shù)用法

  哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無需額外費用,即可穩(wěn)步提升排名至首頁。歡迎體驗最佳的哈爾濱網(wǎng)站建設(shè)。