php - 使用 PHP (DOM) 遍历未知的 XML 结构

标签 php xml arrays parsing loops

我想编写一个函数,将(理论上)未知的 XML 数据结构解析为等效的 PHP 数组。

这是我的示例 XML:

<?xml version="1.0" encoding="UTF-8"?>
<content>

<title>Sample Text</title>

<introduction>
    <paragraph>This is some rudimentary text</paragraph>
</introduction>
<description>
    <paragraph>Here is some more text</paragraph>
    <paragraph>Even MORE text</paragraph>
    <sub_section>
        <sub_para>This is a smaller, sub paragraph</sub_para>
        <sub_para>This is another smaller, sub paragraph</sub_para>
    </sub_section>
</description>
</content>

我从 devarticles 修改了这个 DOM 迭代函数:

$data = 'path/to/xmldoc.xml';
$xmlDoc = new DOMDocument(); #create a DOM element
$xmlDoc->load( $data ); #load data into the element
$xmlRoot = $xmlDoc->firstChild; #establish root

function xml2array($node)
    {
    if ($node->hasChildNodes())
    {
$subNodes = $node->childNodes;
    foreach ($subNodes as $subNode)
        {
        #filter node types
        if (($subNode->nodeType != 3) || (($subNode->nodeType == 3)))   
            {
            $arraydata[$subNode->nodeName]=$subNode->nodeValue;
            }
         xml2array($subNode);
         }
      }
      return $arraydata;
   }
//The getNodesInfo function call

 $xmlarray = xml2array($xmlRoot);


// print the output - with a little bit of formatting for ease of use...
foreach($xmlarray as $xkey)
     {
     echo"$xkey<br/><br/>";
     }

现在,由于我将元素传递到数组的方式,我覆盖了共享节点名称的所有元素(因为我理想情况下希望为键赋予与其原始节点相同的名称)。我的递归不是很好......但是,即使我清空括号 - 第二层节点仍然作为第一层的 values 进入(请参阅描述节点的文本)。

有人知道我如何才能更好地构建它吗?

最佳答案

你最好从网上抓取一些代码

http://www.bin-co.com/php/scripts/xml2array/

    /**
     * xml2array() will convert the given XML text to an array in the XML structure.
     * Link: http://www.bin-co.com/php/scripts/xml2array/
     * Arguments : $contents - The XML text
     *                $get_attributes - 1 or 0. If this is 1 the function will get the attributes as well as the tag values - this results in a different array structure in the return value.
     *                $priority - Can be 'tag' or 'attribute'. This will change the way the resulting array sturcture. For 'tag', the tags are given more importance.
     * Return: The parsed XML in an array form. Use print_r() to see the resulting array structure.
     * Examples: $array =  xml2array(file_get_contents('feed.xml'));
     *              $array =  xml2array(file_get_contents('feed.xml', 1, 'attribute'));
     */
    function xml2array($contents, $get_attributes=1, $priority = 'tag') { 

关于php - 使用 PHP (DOM) 遍历未知的 XML 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1004335/

相关文章:

php - 让使用手机浏览器的用户通过短信发送他们想要的产品代码

php - 根据 woocommerce 类别更改同一产品的默认变体值

php - 邮件发送后显示的html标签

php - phalcon伏特按位运算?

sql - 我可以清理这个 XML 查询吗?

c# - C#中的多维关联数组

xml - 什么时候需要在xml中使用“?

java - XSD 生成一个 MAP<String, Boolean> 属性

javascript - 如何以成对方式添加两个数组

javascript - 使用 ko.observableArray 检查重复项