php json_decode null

來源:互聯網
上載者:User
----- 網上的--------------

http://webhole.net/2009/08/31/how-to-read-json-data-with-php/ 最終解決方案 更新時間 2012年5月31日0:38:42

How To Parse JSON With PHP

------網上找的------------

在網上找了很多,都寫的例子是json_encode.我把我遇到的這個情況寫下吧!

【第一種情況】json_decode 之後什麼都沒有,. 原因之一json_decode只支援utf-8.

iconv('gbk','utf-8', $result_string),用iconv函數改變的編碼格式,我個案是gbk..轉成utf-8.

【第二個情況】 數組對象是需要用print_r ,不能用echo的。

【第三個情況】 之後還有亂碼情況 ..我的個案是這樣的.

header("Content-Type: text/html; charset=UTF-8");

php 我也就拿來就用的.沒啥基礎知識.也沒有很多時間.

【其他情況】

在 http://php.net/manual/en/function.json-decode.php (我在網上下載的php manual chm中竟然 沒有寫這些.真無語... ) 中有寫到:

Example #3 common mistakes using json_decode() 一些大家常常常常常常常常常常常常常常犯的錯誤.. 其他幾個例子也可以看看...


// the following strings are valid JavaScript but not valid JSON

// the name and value must be enclosed in double quotes 1.這裡是說不要使用單引號,正確應該是 $bad_json = '{ "bar": "baz" }';
// single quotes are not valid
$bad_json = "{ 'bar': 'baz' }";
json_decode($bad_json); // null


// the name must be enclosed in double quotes 2.這裡是說 名稱應該要用""包含起來.. 正確的應該是 $bad_json = '{ "bar": "baz" }';就光這個浪費我好幾個小時....弄了半天...哎...
$bad_json = '{ bar: "baz" }';
json_decode($bad_json); // null

// trailing commas are not allowed 3.這裡是說 最後一個不需要逗號.
$bad_json = '{ bar: "baz", }';
json_decode($bad_json); // null

?>

如果我們使用 json_encode() 給含有中文的內容進行編碼時,會出現類似於\u5c71\u4e1c這樣的代碼,雖然使用jQuery或者json_decode()進行解碼的時候,並不會出現問題,但某些時候,我們還是需要將中文原樣的顯示出來。

$code = json_encode( $str );

$code = preg_replace( "#\\\u([0-9a-f]+)#ie" , "iconv('UCS-2', 'UTF-8', pack('H4', '\\1'))" , $code );

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.