php中xml转换json问题

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

php中xml转换json问题

php中xml转换json的方法:

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

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

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

立即学习“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); 
    if ($simpleXmlElementObject == null) { return(EMPTY_STR); }
    $jsonOutput = EMPTY_STR; 
    // Let us convert the XML structure into PHP array structure. $array1 = xml2json::convertSimpleXmlElementObjectIntoArray($simpleXmlElementObject);
    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))
    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.
    if ($recursionDepth > MAX_RECURSION_DEPTH_ALLOWED) { // Fatal error. Exit now. return(null); }
    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) {
    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);    }
    // 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)         // 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;            }            */
            // Let us recursively process the current element we just visited.            // Increase the recursion depth by one.            $recursionDepth++;            $resultArray[$key] =                xml2json::convertSimpleXmlElementObjectIntoArray($value, $recursionDepth);
            // Decrease the recursion depth by one.            $recursionDepth--;        } // End of foreach($simpleXmlElementObject as $key=>$value) {
        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;        }
        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

<?php     require_once("xml2json.php");
    // Filename from where XML contents are to be read.    $testXmlFile = "";
    // Read the filename from the command line.    if ($argc     //Read the XML contents from the input file.    file_exists($testXmlFile) or die('Could not find file ' . $testXmlFile);    $xmlStringContents = file_get_contents($testXmlFile);
    $jsonContents = "";    // Convert it to JSON now.    // xml2json simply takes a String containing XML contents as input.    $jsonContents = xml2json::transformXmlStringToJson($xmlStringContents);
    echo("JSON formatted output generated by xml2json:");    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 实现

            Code Generation in Action        JackHerrington        Manning    
            PHP Hacks        JackHerrington        O'Reilly    
            Podcasting Hacks        JackHerrington        O'Reilly    

登录后复制

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

登录后复制

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。

发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2132986.html

(0)
上一篇 2025年2月24日 23:29:31
下一篇 2025年2月24日 22:06:18

AD推荐 黄金广告位招租... 更多推荐

相关推荐

  • PHP如何使用正则替换中文?

    PHP如何使用正则替换中文? 在PHP中可以使用函数“preg_replace()”进行正则替换,其匹配中文的正则为“/^[x{4e00}-x{9fa5}A-Za-z0-9_]+$/u”,使用时只需将正则、替换字符、字符串依次传入即可。 p…

    2025年2月24日
    200
  • PHP如何开启慢日志查询

    PHP开启慢查询的方法:首先找到“php-fpm”文件;然后去掉“request_slowlog_timeout”前面的分号,并设置时间;接着去掉slowlog前面的分号,并设置log路径;最后重启PHP即可。 PHP开启慢日志查询 推荐:…

    2025年2月24日
    200
  • php post方法有什么用

    php post方法可以使用户上传文本和二进制文件,并且用PHP的认证和文件操作函数,可以完全控制允许哪些人上传以及文件上传后怎样处理,使用语法如“method=”POST””。 POST 方法上传 本特性可以使用户…

    2025年2月24日
    200
  • 怎么关闭php的safe_mode模式呢?

    关闭php的safe_mode模式的方法:首先打开【php.ini】文件;然后将【safe_mode = On】设置为【safe_mode = Off】;最后重启php,或者重启整个环境即可。 关闭php的safe_mode模式的方法: 部…

    2025年2月24日
    200
  • php如何捕获致命错误

    php获取致命错误的方法:首先开启“ob_start”,并建立一个“tmp.php”文件;然后在“short.php”文件中写一些错误代码;最后访问“tmp.php”文件即可。 php捕获致命错误 记录php错误日志可以有力的帮我们查找问题…

    2025年2月24日
    200
  • php怎么知道当前是第几周

    php获取当前是第几周的方法:首先创建一个PHP代码文件;然后设置编码字符;接着输入语句“$week = date(‘W’);”;最后在浏览器中执行该文件即可。 php获取当前是第几周 这就要用到PHP自带的强大的d…

    2025年2月24日
    200
  • php中如何设置cookie

    在php中设置cookie的语法是“setcookie(“user”,$user,time()+3600);”,其中“user”表示用户名,“$user”表示变量的值。 PHP 设置和读取 Cookie 一,设置 C…

    2025年2月24日
    200
  • ubuntu PHP服务器乱码问题

    ubuntu PHP服务器乱码的解决办法:1、使php文件本身的编码与网页的编码应匹配;2、使PHP与数据库的编码应一致,代码为【mysql_query(“set names ‘编码’”);】。 ubun…

    2025年2月24日
    200
  • 如何编译安装PHP?

    如何编译安装PHP? 首先使用“wget”命令将PHP下载并解压; wget http://am1.php.net/distributions/php-7.3.2.tar.gz    tar -zxvf php-7.3.2.tar.gz 登…

    2025年2月24日
    200
  • php如何设置编码为gbk编码

    php设置编码为gbk编码的方法:首先打开需要设置编码的PHP页面;然后在PHP页面的首页部分添加代码语句为“header(“Content-type: text/html; charset=gb2312”);”;最…

    2025年2月24日
    200

发表回复

登录后才能评论