从XML与PHP检索孩子(Retrieving children from XML with PHP

2019-10-30 10:33发布

赫勒在那里,有一个帖子: https://stackoverflow.com/questions/5816786/counting-nodes-in-a-xml-file-using-php我也有同样的问题,但不是数量,我想呼应它。 我对XML的代码:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Root xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<Row>
    <ModeNumber>1</ModeNumber>
    <Mode>online</Mode>
</Row>
<Row>
    <ModeNumber>2</ModeNumber>
    <Mode>mmorpg</Mode>
</Row>

并将此作为PHP:

$xml = simplexml_load_file("include/gamemodes.xml");

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

它只Echo的第一行,没有更多的,我怎么可以把它呼应多行,结果应该是:

ModeNumber: 1
Mode: online
ModeNumber: 2
Mode: mmorpg

对不起,我的英语不好。

Answer 1:

您遍历第一的孩子Row唯一元素。 试试这个:

/* Iterate over all 'Row' elements */
foreach ($xml->Row as $row) 
{
    /* For each 'Row' iterate over all children elements */
    foreach ($row as $child) 
    {
        printf("%s: %s\n", $child->getName(), $child);
    }
}

同样,见,这个简短的演示



文章来源: Retrieving children from XML with PHP