搜索
首页后端开发PHP问题php中xml转换json问题
php中xml转换json问题Jul 23, 2020 am 09:47 AM
jsonphpxml

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 的解决方案有以下几方面的优点:

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

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

  • 很容易承载为 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 string
define ("EMPTY_STR", "");
// SimpleXMLElement object property name for attributes
define ("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&#39;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

<?php
    require_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(&#39;Could not find file &#39; . $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&#39;Reilly</publisher>
    </book>
<br>
    <book id="3">
        <title>Podcasting Hacks</title>
        <author><first>Jack</first><last>Herrington</last></author>
        <publisher>O&#39;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&#39;Reilly"
 }, {
 "@attributes" : {
 "id" : "3"
 }, 
 "title" : "Podcasting Hacks", "author" : {
 "first" : "Jack", "last" : "Herrington"
 }, 
 "publisher" : "O&#39;Reilly"
 }
 ]}
}

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

以上是php中xml转换json问题的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么判断有没有小数点php怎么判断有没有小数点Apr 20, 2022 pm 08:12 PM

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么设置implode没有分隔符php怎么设置implode没有分隔符Apr 18, 2022 pm 05:39 PM

在PHP中,可以利用implode()函数的第一个参数来设置没有分隔符,该函数的第一个参数用于规定数组元素之间放置的内容,默认是空字符串,也可将第一个参数设置为空,语法为“implode(数组)”或者“implode("",数组)”。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
2 周前By尊渡假赌尊渡假赌尊渡假赌
仓库:如何复兴队友
4 周前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒险:如何获得巨型种子
4 周前By尊渡假赌尊渡假赌尊渡假赌

热工具

螳螂BT

螳螂BT

Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中

SublimeText3 英文版

SublimeText3 英文版

推荐:为Win版本,支持代码提示!

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器

将Eclipse与SAP NetWeaver应用服务器集成。

Dreamweaver Mac版

Dreamweaver Mac版

视觉化网页开发工具