Retrieving children from XML with PHP

风流意气都作罢 提交于 2019-12-12 05:46:25

问题


Helle there, There is a post: https://stackoverflow.com/questions/5816786/counting-nodes-in-a-xml-file-using-php I have the same question, but instead of count, I want to echo it. I have this code in 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>

And this as PHP:

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

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

It only echo's the first row and none more, how can I make it to echo multiple rows, the result should be:

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

Sorry for my bad english.


回答1:


You are iterating over the children of the first Row element only. Try this instead:

/* 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);
    }
}

See, also, this short demo.



来源:https://stackoverflow.com/questions/17260041/retrieving-children-from-xml-with-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!