如果没有子级,则从SimpleXMLIterator获取值

时间:2013-09-27 23:48:30

标签: php xml iterator simplexml

请检查此代码,取自here

 <?php
    $xml = <<<XML
    <books>
        <book>
            <title>PHP Basics</title>
            <author>Jim Smith</author>
        </book>
        <book>XML basics</book>
    </books>
    XML;

    $xmlIterator = new SimpleXMLIterator($xml);
    for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
        foreach($xmlIterator->getChildren() as $name => $data) {
        echo "The $name is '$data' from the class " . get_class($data) . "\n";
        }
    }
    ?>

如何使用迭代器从所有书籍节点获取附加“XML基础”(在第二本书节点中)的值?

1 个答案:

答案 0 :(得分:1)

这将为您提供XML basics作为输出。

<?php
    $xml = <<<XML
    <books>
        <book>
            <title>PHP Basics</title>
            <author>Jim Smith</author>
        </book>
        <book>XML basics</book>
    </books>
    XML;
for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
        $xmlIterator->next();
        echo $xmlIterator->getChildren();
    }
?>

[编辑] 它会显示两本书

$xmlIterator = new SimpleXMLIterator($xml);
    for( $xmlIterator->rewind(); $xmlIterator->valid(); $xmlIterator->next() ) {
        foreach($xmlIterator->getChildren() as $name => $data) {
        echo "$data<br />";
        break;
        }
        echo $xmlIterator->getChildren();
    }