简体   繁体   中英

PHP simpleXML - foreach loop run

Actually I'm stuck on running a foreach loop through a simple xml document. The document looks like this:

<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>

So I kinda try to have each node as a single item.

My code:

$xml = simplexml_load_file($outfitUrl);

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

Sadly nothing would show up.

The output of your code is as expected, because the nodes are empty
(though they have data stored inside attributes):

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

If it had a value, it would look like this, and it would be echoed by your code:

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

If you want to retrieve the attributes of those nodes, you need a second foreach -loop:

$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;

}

see it working: https://eval.in/312473

If you know the names of the attributes you want, you can access them directly:

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

    echo $item['url'] . PHP_EOL;

}

If you even know the nodes' names you want, you can go...

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

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

}

see the PHP manual for hints: http://php.net/manual/en/simplexml.examples-basic.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM