php中xml转换json问题
2022-12-02 09:01:16
99
{{single.collect_count}}

php中xml转换json的方法:首先需要使用SimpleXMLElement将XML内容转化成适当的PHP数据类型;然后将PHP数据提供给【Services_JSON】编码器;最后生成最终的JSON格式的输出即可。

php入门到就业线上直播课:进入学习
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API调试工具:点击使用

php中xml转换json的方法:

越来越多的应用程序需要将 XML 转换成 JSON。已经出现了一些基于 Web 的服务来执行这类转换。IBM T.J. Watson Research Center 开发了一种专门的方法,使用 PHP 进行这种转换。该方法以 XML 字符串数据为输入并将其转换成 JSON 格式的数据输出。这种 PHP 的解决方案有以下几方面的优点:

  • 可以独立模式运行,在命令行下执行。

  • 可以包含到已有服务器端代码工件中。

  • 很容易承载为 Web 上的 Web 服务。

XML 到 JSON 的转换需要用到两种 PHP 核心特性:

  • SimpleXMLElement

  • Services_JSON

只需要这两种 PHP 核心特性,就可以将任何 XML 数据转化成 JSON。首先,需要使用 SimpleXMLElement 将 XML 内容转化成适当的 PHP 数据类型。然后将 PHP 数据提供给 Services_JSON 编码器,后者再生成最终的 JSON 格式的输出。

相关学习推荐:PHP编程从入门到精通

理解 PHP 代码

这个 xml2json 实现包括三部分:

  • xml2json.php —— 这个 PHP 类包括两个静态函数

  • xml2json_test.php —— 执行xml2json 转换函数的测试驱动程序

  • test1.xml、test2.xml、test3.xml、test4.xml —— 复杂程度不同的 XML 文件

为了简化起见,本文省略了代码中的详细注释。不过后面附的源文件中包含完整的注释。要了解完全的程序逻辑细节,请参阅所附的源文件(请参阅下载)。

(1)定义了一些要用到的常量。第一行代码导入了 Services_JSON 实现。

(1)定义 xml2json.php 中的常量

require_once 'json/JSON.php';// Internal program-specific Debug option.define ("DEBUG", false);// Maximum Recursion Depth that we can allow.define ("MAX_RECURSION_DEPTH_ALLOWED", 25);// An empty stringdefine ("EMPTY_STR", "");// SimpleXMLElement object property name for attributesdefine ("SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES", "@attributes");// SimpleXMLElement object name.define ("SIMPLE_XML_ELEMENT_PHP_CLASS", "SimpleXMLElement");
登录后复制

(2)中的代码片段是 xml2json 转换器的入口函数。它接收 XML 数据作为输入,将 XML 字符串转化成 SimpleXMLElement 对象,然后发送给该类的另一个(递归)函数作为输入。这个函数将 XML 元素转化成 PHP 关联数组。这个数组再被传给 Services_JSON 编码器作为其输入,该编码器给出 JSON 格式的输出。

(2)使用 xml2json.php 中的 Services_JSON

public static function transformXmlStringToJson($xmlStringContents) { $simpleXmlElementObject = simplexml_load_string($xmlStringContents); <br>if ($simpleXmlElementObject == null) { return(EMPTY_STR); }<br>$jsonOutput = EMPTY_STR; <br>// Let us convert the XML structure into PHP array structure. $array1 = xml2json::convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject);<br>if (($array1 != null) && (sizeof($array1) > 0)) {// Create a new instance of Services_JSON $json = new Services_JSON(); // Let us now convert it to JSON formatted data. $jsonOutput = $json->encode($array1); } // End of if (($array1 != null) && (sizeof($array1) > 0))<br>return($jsonOutput); } // End of function transformXmlStringToJson
登录后复制

(3)这段长长的代码片段采用了 PHP 开放源码社区(请参阅参考资料)提出的递归技术。它接收输入的 SimpleXMLElement 对象,沿着嵌套的 XML 树递归遍历。将访问过的 XML 元素保存在 PHP 关联数组中。可以通过修改4中定义的常量来改变最大递归深度。

(3)xml2json.php 中的转换逻辑

public static function convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject,&$recursionDepth=0) { // Keep an eye on how deeply we are involved in recursion.<br>if ($recursionDepth > MAX_RECURSION_DEPTH_ALLOWED) { // Fatal error. Exit now. return(null); }<br>if ($recursionDepth == 0) { if (get_class($simpleXmlElementObject) != SIMPLE_XML_ELEMENT_PHP_CLASS) { // If the external caller doesn't call this function initially // with a SimpleXMLElement object, return now. return(null); } else { // Store the original SimpleXmlElementObject sent by the caller. // We will need it at the very end when we return from here for good. $callerProvidedSimpleXmlElementObject = $simpleXmlElementObject; } } // End of if ($recursionDepth == 0) {<br>if (get_class($simpleXmlElementObject) == SIMPLE_XML_ELEMENT_PHP_CLASS) {// Get a copy of the simpleXmlElementObject$copyOfsimpleXmlElementObject = $simpleXmlElementObject;// Get the object variables in the SimpleXmlElement object for us to iterate.$simpleXmlElementObject = get_object_vars($simpleXmlElementObject);}<br>// It needs to be an array of object variables.if (is_array($simpleXmlElementObject)) {// Is the array size 0? Then, we reached the rare CDATA text if any.if (count($simpleXmlElementObject) <= 0) {// Let us return the lonely CDATA. It could even be// an empty element or just filled with whitespaces.return (trim(strval($copyOfsimpleXmlElementObject)));}<br>// Let us walk through the child elements now.foreach($simpleXmlElementObject as $key=>$value) {// When this block of code is commented, XML attributes will be// added to the result array.// Uncomment the following block of code if XML attributes are// NOT required to be returned as part of the result array./*if($key == SIMPLE_XML_ELEMENT_OBJECT_PROPERTY_FOR_ATTRIBUTES) {continue;}*/<br>// Let us recursively process the current element we just visited.// Increase the recursion depth by one.$recursionDepth++;$resultArray[$key] =xml2json::convertSimpleXmlElementObjectIntoArray($value, $recursionDepth);<br>// Decrease the recursion depth by one.$recursionDepth--;} // End of foreach($simpleXmlElementObject as $key=>$value) {<br>if ($recursionDepth == 0) {// That is it. We are heading to the exit now.// Set the XML root element name as the root [top-level] key of// the associative array that we are going to return to the caller of this// recursive function.$tempArray = $resultArray;$resultArray = array();$resultArray[$callerProvidedSimpleXmlElementObject->getName()] = $tempArray;}<br>return ($resultArray);} else {// We are now looking at either the XML attribute text or// the text between the XML tags.return (trim(strval($simpleXmlElementObject)));} // End of else} // End of function convertSimpleXmlElementObjectIntoArray.
登录后复制

成功遍历 XML 树之后,该函数就用 PHP 关联数组转换和存储了所有的 XML 元素(根元素和所有的孩子元素)。复杂的 XML 文档,得到的 PHP 数组也同样复杂。一旦 PHP 数组构造完成,Services_JSON 编码器就很容易将其转化成 JSON 格式的数据了。要了解其中的递归逻辑,请参阅存档的源文件。

xml2json 测试驱动程序的实现

(4)中的代码片段是一个用于执行 xml2json 转换器逻辑的测试驱动程序。

(4)xml2json_test.php

<?phprequire_once("xml2json.php");<br>// Filename from where XML contents are to be read.$testXmlFile = "";<br>// Read the filename from the command line.if ($argc <= 1) {print("Please provide the XML filename as a command-line argument:\n");print("\tphp -f xml2json_test.php test1.xml\n");return;} else {$testXmlFile = $argv[1];}<br>//Read the XML contents from the input file.file_exists($testXmlFile) or die('Could not find file ' . $testXmlFile);$xmlStringContents = file_get_contents($testXmlFile);<br>$jsonContents = "";// Convert it to JSON now.// xml2json simply takes a String containing XML contents as input.$jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);<br>echo("JSON formatted output generated by xml2json:\n\n");echo($jsonContents);?>
登录后复制

可以在命令行中运行该程序,输入以下 XML 文件名作为命令行参数:

php -f xml2json_test.php test2.xml
登录后复制

在命令行中执行的时候,该程序将 XML 内容从文件读入一个字符串变量。然后调用 xml2json 类中的静态函数得到 JSON 格式的结果。除了从命令行中运行该程序之外,还可以修改这个源文件中的逻辑来公开 xml2json 转换器,将其作为可使用简单对象访问协议(SOAP)或者 Representational State Transfer (REST) 访问协议来远程调用的 Web 服务。如果需要,在 PHP 中只要稍加修改就能实现此远程调用。

(5)展示了本文提供的四个测试 XML 文件中的一个,这些文件用于测试 xml2json 实现。他们的复杂度各不相同。可以将这些文件作为命令行参数传递给测试驱动程序 xml2json_test.php。

(5)用 test2.xml 测试 xml2json 实现

<?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><br><book id="2"><title>PHP Hacks</title><author><first>Jack</first><last>Herrington</last></author><publisher>O'Reilly</publisher></book><br><book id="3"><title>Podcasting Hacks</title><author><first>Jack</first><last>Herrington</last></author><publisher>O'Reilly</publisher></book></books>
登录后复制

(6)中所示的代码片段是,使用 test2.xml 作为测试驱动程序 xml2json_test.php 的命令行参数时得到的 JSON 格式结果。

(6)test2.xml 的 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" } ]}}
登录后复制

请注意,<book> 元素的 XML 属性 id 作为 "@attributes" 对象的属性被保存在 JSON 数据中,<book> 元素作为对象数组被保存在 JSON 数据中。JSON 输出易于在 JavaScript 代码中使用 eval 语句进行处理。

以上就是php中xml转换json问题的详细内容,更多请关注php中文网其它相关文章!

回帖
全部回帖({{commentCount}})
{{item.user.nickname}} {{item.user.group_title}} {{item.friend_time}}
{{item.content}}
{{item.comment_content_show ? '取消' : '回复'}} 删除
回帖
{{reply.user.nickname}} {{reply.user.group_title}} {{reply.friend_time}}
{{reply.content}}
{{reply.comment_content_show ? '取消' : '回复'}} 删除
回帖
收起
没有更多啦~
{{commentLoading ? '加载中...' : '查看更多评论'}}