PHP simpleXML - foreach循环运行

时间:2015-04-12 15:14:09

标签: php xml

实际上我一直在通过简单的xml文档运行foreach循环。该文件如下:

<outfits>
    <outfit default="1" skin="0xFCDBBA" species="stud">
        <head url="http://assets.zwinky.com/assets/stud/heads/01/head1" c="0xF2B38A" c2="0xffffff" z="33000"/>
        <face url="http://assets.zwinky.com/assets/stud/faces/01/stud3" c="0x996633" c2="0xffffff" z="34000"/>
        <midsection url="http://assets.zwinky.com/assets/stud/midsections/01/ms1" z="9000"/>
        <leg url="http://assets.zwinky.com/assets/stud/legs/01/legs1" z="10000"/>
        <hair url="http://assets.zwinky.com/assets/stud/hair/01/hr11" c="0x5C1C01" c2="0xffffff" z="37000"/>
    </outfit>
</outfits>

所以我尝试将每个节点作为单个项目。

我的代码:

$xml = simplexml_load_file($outfitUrl);

foreach($xml->outfit->children() as $item) {
    echo $item;
}

可悲的是,没有任何东西会出现。

1 个答案:

答案 0 :(得分:0)

您的代码输出符合预期,因为节点为空
(尽管他们将数据存储在属性中):

<leg url="http://assets.zwinky.com/assets/stud/legs/01/legs1" z="10000"/>

如果它有一个值,它看起来像这样,它会被你的代码回应:

<leg url="http://someurl" z="10000">This is a node value.</leg>

如果要检索这些节点的属性,则需要第二个foreach - 循环:

$xml = simplexml_load_string($x); // assume XML in $x

foreach ($xml->outfit->children() as $item) {

    // this loop will display all attributes of the current node:
    foreach ($item->attributes() as $att => $attvalue)
        echo "$att: $attvalue" . PHP_EOL;

}

看到它有效:https://eval.in/312473

如果您知道所需属性的名称,可以直接访问它们:

foreach ($xml->outfit->children() as $item) {

    echo $item['url'] . PHP_EOL;

}

如果你甚至知道你想要的节点名称,你可以去......

foreach ($xml->outfit as $outfit) {

    echo $outfit['species'] . PHP_EOL;
    echo $outfit->hair['url'] . PHP_EOL;
    echo $outfit->face['url'] . PHP_EPÖ;
    // etc.

}

请参阅PHP手册以获取提示:http://php.net/manual/en/simplexml.examples-basic.php