Zend_Json 簡介 --(手冊)

weixin_33896726發表於2017-05-25


1.  簡單介紹


Zend_Json 提供一個方便的方式來串聯(native的)PHP(的變數)和JSON,並將JSON(物件)解碼到PHP中。


2.  基本使用方法


Zend_Json的使用包含使用現有的兩個公共的static方法 : Zend_Json::encode() 和Zend_Json::decode().

// 獲得一個value:
$phpNative = Zend_Json::decode($encodedValue);
// 編碼並返回給client:
$json = Zend_Json::encode($phpNative);

3.  JSON物件

 

JSON不同意物件引用,能夠將JSON物件解碼作為關聯陣列,而且返回一個物件。

 

// 解碼 JSON 物件作為 PHP 物件
$phpNative = Zend_Json::decode($encodedValue, Zend_Json::TYPE_OBJECT);


4.  XML到JSON的轉換

 

Zend_Json 包含一個叫做 Zend_Json::fromXml() 的靜態方法,它將從給定的 XML 的輸入生成 JSON。

呼叫函式示範:

// fromXml function simply takes a String containing XML contents as input.
$jsonContents = Zend_Json::fromXml($xmlStringContents, true);?>

    Zend_Json::fromXml() 函式執行XML 格式的字串輸入和返回等同的 JSON 格式字串的輸出的轉換,假設有不論什麼 XML 輸入格式錯誤或者轉換邏輯錯誤,它將丟擲一個異常。

轉換邏輯也使用遞迴技術來遍歷XML 樹。它支援 25 級遞迴。假設遞迴超過這個深度,它將丟擲一個 Zend_Json_Exception

XML輸入字串傳遞給 Zend_Json::fromXml() 函式:

<?xml version="1.0" encoding="UTF-8"?>
<books>
    <book id="1">
        <title>Code Generation in Action</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>Manning</publisher>
    </book>
 
    <book id="2">
        <title>PHP Hacks</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>O'Reilly</publisher>
    </book>
 
    <book id="3">
        <title>Podcasting Hacks</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>O'Reilly</publisher>
    </book>
</books> ?

>


從 Zend_Json::fromXml() 函式返回的 JSON 輸出字串:

{
   "books" : {
      "book" : [ {
         "@attributes" : {
            "id" : "1"
         },
         "title" : "Code Generation in Action",
         "author" : {
            "first" : "Jack", "last" : "Herrington"
         },
         "publisher" : "Manning"
      }, {
         "@attributes" : {
            "id" : "2"
         },
         "title" : "PHP Hacks", "author" : {
            "first" : "Jack", "last" : "Herrington"
         },
         "publisher" : "O'Reilly"
      }, {
         "@attributes" : {
            "id" : "3"
         },
         "title" : "Podcasting Hacks", "author" : {
            "first" : "Jack", "last" : "Herrington"
         },
         "publisher" : "O'Reilly"
      }
   ]}
}  ?>
 
    
 



相關文章