dongzhent208577 2013-06-23 10:56
浏览 27
已采纳

使用PHP从XML中检索子项

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条回答 默认 最新

  • dqroktbn005028 2013-06-23 11:25
    关注

    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
    ", $child->getName(), $child);
        }
    }
    

    See, also, this short demo.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看