Zend_Json 简单介绍 --(手册)


1.  简介


Zend_Json 提供一个方便的方式来串联(native的)PHP(的变量)和JSON,并将JSON(对象)解码到PHP中。


2.  基本用法


Zend_Json的使用包括使用现有的两个公共的static方法 : Zend_Json::encode() 和Zend_Json::decode().

// 获得一个value:
$phpNative = Zend_Json::decode($encodedValue);
// 编码并返回给客户端:
$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"
      }
   ]}
}  ?>
 
    
 



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值