麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > PHP > 正文

php語言中使用json的技巧及json的實現代碼詳解

2024-05-04 23:39:52
字體:
來源:轉載
供稿:網友

json是一種比較流行的數據交換格式之一,各大API網站均支持json。通過本篇文章給大家介紹php語言中使用json技巧以及php語言中json的實現,對php語言中使用json技巧及json的實現代碼詳解感興趣的朋友一起來本文學習學習吧

目前,JSON已經成為最流行的數據交換格式之一,各大網站的API幾乎都支持它。

我寫過一篇《數據類型和JSON格式》,探討它的設計思想。今天,我想總結一下PHP語言對它的支持,這是開發互聯網應用程序(特別是編寫API)必須了解的知識。

從5.2版本開始,PHP原生提供json_encode()和json_decode()函數,前者用于編碼,后者用于解碼。

一、json_encode()

該函數主要用來將數組和對象,轉換為json格式。先看一個數組轉換的例子:
 

  1. $arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5); 
  2. echo json_encode($arr); 

結果為

{"a":1,"b":2,"c":3,"d":4,"e":5}

再看一個對象轉換的例子:

 

 
  1. $obj->body = 'another post'
  2. $obj->id = 21; 
  3. $obj->approved = true
  4. $obj->favorite_count = 1; 
  5. $obj->status = NULL; 
  6. echo json_encode($obj); 

結果為

 

 
  1.     "body":"another post",  
  2.     "id":21, 
  3.     "approved":true
  4.     "favorite_count":1, 
  5.     "status":null 

由于json只接受utf-8編碼的字符,所以json_encode()的參數必須是utf-8編碼,否則會得到空字符或者null。當中文使用GB2312編碼,或者外文使用ISO-8859-1編碼的時候,這一點要特別注意。

二、索引數組和關聯數組

PHP支持兩種數組,一種是只保存"值"(value)的索引數組(indexed array),另一種是保存"名值對"(name/value)的關聯數組(associative array)。

由于javascript不支持關聯數組,所以json_encode()只將索引數組(indexed array)轉為數組格式,而將關聯數組(associative array)轉為對象格式。

比如,現在有一個索引數組

 

 
  1. $arr = Array('one''two''three'); 
  2. echo json_encode($arr); 

結果為:

["one","two","three"]

如果將它改為關聯數組:

 

 
  1. $arr = Array('1'=>'one''2'=>'two''3'=>'three'); 
  2. echo json_encode($arr); 

結果就變了:

 

 
  1. {"1":"one","2":"two","3":"three"

注意,數據格式從"[]"(數組)變成了"{}"(對象)。

如果你需要將"索引數組"強制轉化成"對象",可以這樣寫

 

 
  1. json_encode( (object)$arr ); 

或者

 

 
  1. json_encode ( $arr, JSON_FORCE_OBJECT ); 

三、類(class)的轉換

下面是一個PHP的類:

 

 
  1. class Foo { 
  2.     const ERROR_CODE = '404'
  3.     public $public_ex = 'this is public'
  4.     private $private_ex = 'this is private!'
  5.     protected $protected_ex = 'this should be protected'
  6.     public function getErrorCode() { 
  7.       return self::ERROR_CODE; 
  8.     } 

現在,對這個類的實例進行json轉換:

 

 
  1. $foo = new Foo; 
  2. $foo_json = json_encode($foo); 
  3. echo $foo_json; 

輸出結果是

{"public_ex":"this is public"}

可以看到,除了公開變量(public),其他東西(常量、私有變量、方法等等)都遺失了。

四、json_decode()

該函數用于將json文本轉換為相應的PHP數據結構。下面是一個例子:

 

 
  1. $json = '{"foo": 12345}';   
  2. $obj = json_decode($json);  
  3. print $obj->{'foo'}; // 12345 

通常情況下,json_decode()總是返回一個PHP對象,而不是數組。比如:

 

 
  1. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';   
  2. var_dump(json_decode($json)); 

結果就是生成一個PHP對象:

 

 
  1. object(stdClass)#1 (5) { 
  2.    
  3.     ["a"] => int(1) 
  4.     ["b"] => int(2) 
  5.     ["c"] => int(3) 
  6.     ["d"] => int(4) 
  7.     ["e"] => int(5) 
  8.    

如果想要強制生成PHP關聯數組,json_decode()需要加一個參數true:

 

 
  1. $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'
  2. var_dump(json_decode($json,true)); 

結果就生成了一個關聯數組:

 

 
  1. array(5) { 
  2.    
  3.      ["a"] => int(1) 
  4.      ["b"] => int(2) 
  5.      ["c"] => int(3) 
  6.      ["d"] => int(4) 
  7.      ["e"] => int(5) 
  8.    
  9. }  

五、json_decode()的常見錯誤

下面三種json寫法都是錯的,你能看出錯在哪里嗎?

 

 
  1. $bad_json = "{ 'bar': 'baz' }"
  2. $bad_json = '{ bar: "baz" }';   
  3. $bad_json = '{ "bar": "baz", }'

對這三個字符串執行json_decode()都將返回null,并且報錯。

第一個的錯誤是,json的分隔符(delimiter)只允許使用雙引號,不能使用單引號。第二個的錯誤是,json名值對的"名"(冒號左邊的部分),任何情況下都必須使用雙引號。第三個的錯誤是,最后一個值之后不能添加逗號(trailing comma)。

另外,json只能用來表示對象(object)和數組(array),如果對一個字符串或數值使用json_decode(),將會返回null。

 

 
  1. var_dump(json_decode("Hello World")); //null 

下面給大家介紹哦php語言的json實現

由于開發一個ajax file manager for web開源項目,數據交換使用的json格式,后來發現在低版本的php上運行會有問題,仔細調試發現json_decode和json_encode無法正常工作,于是查閱資料,發現低版本的php沒有實現這兩個函數,為了兼容性,我只好自己實現一個php版的json編碼解碼代碼,并保證和json2.js的一致,測試調試并通過,現在將其公布出來,供有相同需求的同學使用:

 

 
  1. <?php  
  2. /* * ****************************************************************************  
  3. * $base: $  
  4.  
  5. * $Author: $  
  6. * Berlin Qin  
  7.  
  8. * $History: base.js $  
  9. * Berlin Qin // created  
  10.  
  11. * $contacted  
  12. [email protected]  
  13. * www.webfmt.com  
  14.  
  15. * *************************************************************************** */ 
  16. /* ===========================================================================  
  17. * license  
  18.  
  19. * 、Open Source Licenses  
  20. * webfmt is distributed under the GPL, LGPL and MPL open source licenses.  
  21. * This triple copyleft licensing model avoids incompatibility with other open source licenses.  
  22. * These Open Source licenses are specially indicated for:  
  23. * Integrating webfmt into Open Source software;  
  24. * Personal and educational use of webfmt;  
  25. * Integrating webfmt in commercial software,  
  26. * taking care of satisfying the Open Source licenses terms,  
  27. * while not able or interested on supporting webfmt and its development.  
  28.  
  29. * 、Commercial License – fbis source Closed Distribution License - CDL  
  30. * For many companies and products, Open Source licenses are not an option.  
  31. * This is why the fbis source Closed Distribution License (CDL) has been introduced.  
  32. * It is a non-copyleft license which gives companies complete freedom  
  33. * when integrating webfmt into their products and web sites.  
  34. * This license offers a very flexible way to integrate webfmt in your commercial application.  
  35. * These are the main advantages it offers over an Open Source license:  
  36. * Modifications and enhancements doesn't need to be released under an Open Source license;  
  37. * There is no need to distribute any Open Source license terms alongside with your product  
  38. * and no reference to it have to be done;  
  39. * No references to webfmt have to be done in any file distributed with your product;  
  40. * The source code of webfmt doesn't have to be distributed alongside with your product;  
  41. * You can remove any file from webfmt when integrating it with your product.  
  42. * The CDL is a lifetime license valid for all releases of webfmt published during  
  43. * and before the year following its purchase.  
  44. * It's valid for webfmt releases also. It includes year of personal e-mail support.  
  45.  
  46. * ************************************************************************************************************************************************* */ 
  47. function jsonDecode($json)  
  48. {  
  49. $result = array();  
  50. try 
  51. {  
  52. if (PHP_VERSION_ID > )  
  53. {  
  54. $result = (array) json_decode($json);  
  55. }  
  56. else 
  57. {  
  58. $json = str_replace(array("////", "///""), array("&#;""&#;"), $json);  
  59. $parts = preg_split("@(/"[^/"]*/")|([/[/]/{/},:])|/s@is", $json, -, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);  
  60. foreach ($parts as $index => $part)  
  61. {  
  62. if (strlen($part) == )  
  63. {  
  64. switch ($part)  
  65. {  
  66. case "[":  
  67. case "{":  
  68. $parts[$index] = "array(";  
  69. break;  
  70. case "]":  
  71. case "}":  
  72. $parts[$index] = ")";  
  73. break;  
  74. case ":":  
  75. $parts[$index] = "=>";  
  76. break;  
  77. case ",":  
  78. break;  
  79. default:  
  80. break;  
  81. }  
  82. }  
  83. }  
  84. $json = str_replace(array("&#;""&#;""$"), array("////", "///"""//$"), implode("", $parts));  
  85. $result = eval("return $json;");  
  86. }  
  87. }  
  88. catch (Exception $e)  
  89. {  
  90. $result = array("error" => $e->getCode());  
  91. }  
  92. return $result;  
  93. }  
  94. function valueTostr($val)  
  95. {  
  96. if (is_string($val))  
  97. {  
  98. $val = str_replace('/"', "///"", $val);  
  99. $val = str_replace("//", "////", $val);  
  100. $val = str_replace("/""///", $val);  
  101. $val = str_replace("/t""//t", $val);  
  102. $val = str_replace("/n""//n", $val);  
  103. $val = str_replace("/r""//r", $val);  
  104. $val = str_replace("/b""//b", $val);  
  105. $val = str_replace("/f""//f", $val);  
  106. return '"' . $val . '"';  
  107. }  
  108. elseif (is_int($val))  
  109. return sprintf('%d', $val);  
  110. elseif (is_float($val))  
  111. return sprintf('%F', $val);  
  112. elseif (is_bool($val))  
  113. return ($val ? 'true' : 'false');  
  114. else 
  115. return 'null';  
  116. }  
  117. function jsonEncode($arr)  
  118. {  
  119. $result = "{}";  
  120. try 
  121. {  
  122. if (PHP_VERSION_ID > )  
  123. {  
  124. $result = json_encode($arr);  
  125. }  
  126. else 
  127. {  
  128. $parts = array();  
  129. $is_list = false;  
  130. if (!is_array($arr))  
  131. {  
  132. $arr = (array) $arr;  
  133. }  
  134. $end = count($arr) - ;  
  135. if (count($arr) > )  
  136. {  
  137. if (is_numeric(key($arr)))  
  138. {  
  139. $result = "[";  
  140. for ($i = ; $i < count($arr); $i++)  
  141. {  
  142. if (is_array($arr[$i]))  
  143. {  
  144. $result = $result . jsonEncode($arr[$i]);  
  145. }  
  146. else 
  147. {  
  148. $result = $result . valueTostr($arr[$i]);  
  149. }  
  150. if ($i != $end)  
  151. {  
  152. $result = $result . ",";  
  153. }  
  154. }  
  155. $result = $result . "]";  
  156. }  
  157. else 
  158. {  
  159. $result = "{";  
  160. $i = ;  
  161. foreach ($arr as $key => $value)  
  162. {  
  163. $result = $result . '"' . $key . '":';  
  164. if (is_array($value))  
  165. {  
  166. $result = $result . jsonEncode($value);  
  167. }  
  168. else 
  169. {  
  170. $result = $result . valueTostr($value);  
  171. }  
  172. if ($i != $end)  
  173. {  
  174. $result = $result . ",";  
  175. }  
  176. $i++;  
  177. }  
  178. $result = $result . "}";  
  179. }  
  180. }  
  181. else 
  182. {  
  183. $result = "[]";  
  184. }  
  185. }  
  186. }  
  187. catch (Exception $e)  
  188. {  
  189. }  
  190. return $result;  
  191. }  
  192. ?> 

如果使用過程有什么問題,可以給我email.歡迎大家指出錯誤!

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黄色av电影在线 | 91短视频在线| 一级黄色av电影 | 久国久产久精永久网页 | 一分钟免费观看完整版电影 | 国产成人精品网站 | 国产妇女乱码一区二区三区 | 色婷婷久久久久久 | 日韩一级成人 | 免费久久久久久久 | av一道本| 高清在线观看av | 91一级毛片| 中文字幕免费在线观看视频 | 国产理论视频在线观看 | 国产妞干网 | 久久在线精品视频 | 成人免费福利网站 | 亚洲欧美aⅴ| 国产一区精品在线观看 | 康妮卡特欧美精品一区 | 久久久久久久久久久久久国产精品 | 双性精h调教灌尿打屁股的文案 | 舌头伸进添的我好爽高潮网站 | 欧美18—19sex性护士中国 | 男女羞羞视频在线免费观看 | 欧美成人国产va精品日本一级 | 91成人免费看片 | 成人免费一区二区三区 | 一区二区三区日韩 | 青青草最新网址 | 特级黄色一级毛片 | 黄色毛片视频在线观看 | 失禁高潮抽搐喷水h | 99视频有精品视频高清 | 国产在线精品一区二区夜色 | 国产1区2| 免费久久久久 | va视频在线 | 欧洲成人综合网 | 亚洲国产精品500在线观看 |