php中xml转换jon问题

2025-04-13 10:45:02 4
  • 收藏
  • 管理
    php中xml转换json的方法:首先需要使用SimpleXMLElement将XML内容转化成适当的PHP数据类型;然后将PHP数据提供给【Services_JSON】编码器;最后生成最终的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 复制publicstaticfunction 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 =newServices_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 中的转换逻辑 复制publicstaticfunction 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 doesnt 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)<=0){// Let us return the lonely CDATA. It could even be// an empty element or just filled with whitespaces.return(trim(strval($copyOfsimpleXmlElementObject)));}
    // 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 复制// Filename from where XML contents are to be read. $testXmlFile ="";
    // 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];}
    //Read the XML contents from the input file. file_exists($testXmlFile)ordie(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:\\\\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 实现 复制Code Generation in ActionJackHerringtonManning
    PHP HacksJackHerringtonOReilly
    Podcasting HacksJackHerringtonOReilly
    (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":"OReilly"},{"@attributes":{"id":"3"},"title":"Podcasting Hacks","author":{"first":"Jack","last":"Herrington"},"publisher":"OReilly"}]}} 请注意, 元素的 XML 属性 id 作为 "@attributes" 对象的属性被保存在 JSON 数据中, 元素作为对象数组被保存在 JSON 数据中。JSON 输出易于在 JavaScript 代码中使用 eval 语句进行处理。
    上一页:php中ytem和exec的区别是什么? 下一页:php中while循环语句如何使用
    全部评论(0)