使用PHP从XML检索子级 [英] Retrieving children from XML with PHP

查看:80
本文介绍了使用PHP从XML检索子级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Helle那里,
有一条帖子: https ://stackoverflow.com/questions/5816786/counting-nodes-in-a-xml-file-using-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>

这是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.

推荐答案

您仅在第一个 Row 元素的子级上进行迭代。改为尝试以下操作:

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.

这篇关于使用PHP从XML检索子级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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