PHP - 简单 XML - 嵌套层次结构 [英] PHP - Simple XML - Nested Hierarchy

查看:30
本文介绍了PHP - 简单 XML - 嵌套层次结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用 PHP 的简单 XML 函数来处理 XML 文件.

I have been using PHP's simple XML function to work with an XML file.

以下代码适用于简单的 XML 层次结构:

The below code works fine for a simple XML hierarchy:

$xml = simplexml_load_file("test.xml");

echo $xml->getName() . "<br />";

foreach($xml->children() as $child)
{
    echo $child->getName() . ": " . $child . "<br />";
}

这里假设 XML 文档的结构如下:

This assumes the structure of the XML document is as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>
<note>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

但是,如果我的 XML 文档中有更复杂的结构 - 内容根本不会输出.下面显示了一个更复杂的 XML 示例:

However, if I had a more complex structure within my XML document - the contents simply is not output. A more complex XML example is shown below:

<note>
    <noteproperties>
        <notetype>
            TEST
        </notetype>
    </noteproperties>
    <to>Tove</to>
    <from>Jani</from>
    <heading>Reminder</heading>
    <body>Don't forget me this weekend!</body>
</note>

我需要处理深度不确定的 XML 文件 - 谁能建议一种方法?

I need to process XML files that have an indefinite depth - can anyone suggest a method?

推荐答案

那是因为你需要在

看看这个,来自SimpleXMLElement::children的例子:

Check this out, example from SimpleXMLElement::children:

$xml = new SimpleXMLElement(
'<person>
     <child role="son">
         <child role="daughter"/>
     </child>
     <child role="daughter">
         <child role="son">
             <child role="son"/>
         </child>
     </child>
 </person>');

foreach ($xml->children() as $second_gen) {
    echo ' The person begot a ' . $second_gen['role'];

    foreach ($second_gen->children() as $third_gen) {
        echo ' who begot a ' . $third_gen['role'] . ';';

        foreach ($third_gen->children() as $fourth_gen) {
            echo ' and that ' . $third_gen['role'] .
                ' begot a ' . $fourth_gen['role'];
        }
    }
}

这篇关于PHP - 简单 XML - 嵌套层次结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆