(轉)在PHP語言中使用JSON,phpjson_PHP教程

來源:互聯網
上載者:User

(轉)在PHP語言中使用JSON,phpjson


原文 :

http://www.ruanyifeng.com/blog/2011/01/json_in_php.html

------------------------------------------------------------------------

作者: 阮一峰

日期: 2011年1月14日

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

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

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

一、json_encode()

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

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

結果為

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

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

$obj->body           = 'another post';  $obj->id             = 21;  $obj->approved       = true;  $obj->favorite_count = 1;  $obj->status         = NULL;  echo json_encode($obj);

結果為

{    "body":"another post",      "id":21,      "approved":true,      "favorite_count":1,      "status":null}   

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

二、索引數組和關聯陣列

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

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

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

$arr = Array('one', 'two', 'three');  echo json_encode($arr);

結果為:

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

如果將它改為關聯陣列:

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

結果就變了:

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

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

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

json_encode( (object)$arr );

或者

json_encode ( $arr, JSON_FORCE_OBJECT );

三、類(class)的轉換

下面是一個PHP的類:

class Foo {      const     ERROR_CODE = '404';      public    $public_ex = 'this is public';      private   $private_ex = 'this is private!';      protected $protected_ex = 'this should be protected';        public function getErrorCode() {        return self::ERROR_CODE;      }  }  

現在,對這個類的執行個體進行json轉換:

$foo = new Foo;  $foo_json = json_encode($foo);  echo $foo_json;

輸出結果是

{"public_ex":"this is public"} 

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

四、json_decode()

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

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

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

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

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

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

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

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

結果就產生了一個關聯陣列:

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

五、json_decode()的常見錯誤

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

$bad_json = "{ 'bar': 'baz' }";  $bad_json = '{ bar: "baz" }';  $bad_json = '{ "bar": "baz", }';

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

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

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

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

六、參考材料

[1] PHP Manual

[2] Ed Finkler, JSON is Everybody's Friend

http://www.bkjia.com/PHPjc/1064532.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1064532.htmlTechArticle(轉)在PHP語言中使用JSON,phpjson 原文 : http://www.ruanyifeng.com/blog/2011/01/json_in_php.html --------------------------------------------------------------------...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.