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" } ]} } ?>