linux007
1/30/2013 - 10:19 PM

PHP SPL SimpleXMLIterator examples

PHP SPL SimpleXMLIterator examples

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<document>
    <animal>
        <category id="26">
            <species>Phascolarctidae</species>
            <type>koala</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="27">
            <species>macropod</species>
            <type>kangaroo</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="28">
            <species>diprotodon</species>
            <type>wombat</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="31">
            <species>macropod</species>
            <type>wallaby</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="21">
            <species>dromaius</species>
            <type>emu</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="22">
            <species>Apteryx</species>
            <type>kiwi</type>
            <name>Troy</name>
        </category>
    </animal>
    <animal>
        <category id="23">
            <species>kingfisher</species>
            <type>kookaburra</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="48">
            <species>monotremes</species>
            <type>platypus</type>
            <name>Bruce</name>
        </category>
    </animal>
    <animal>
        <category id="4">
            <species>arachnid</species>
            <type>funnel web</type>
            <name>Bruce</name>
            <legs>8</legs>
        </category>
    </animal>
</document>
<?php
try {
    $sxi = new SimpleXMLIterator($xmlstring);
    $foo = $sxi->xpath('animal/category/species');
    foreach ($foo as $k=>$v) {
        echo $v . '<br />';
    }
}
catch(Exception $e) {
    echo $e->getMessage();
}
<?php
try {
    $sxi = new SimpleXMLIterator($xmlstring);
    $sxi->addChild('animal', 'Tiger');
    $new = new SimpleXmlIterator($sxi->saveXML());
    foreach($new as $val) {
        echo $val.'<br />';
    }
}
catch(Exception $e) {
    echo $e->getMessage();
}
<?php
try {
    $sxe = simplexml_load_string($xmlstring, 'SimpleXMLIterator');
    for ($sxe->rewind(); $sxe->valid(); $sxe->next()) {
        if ($sxe->hasChildren()) {
            foreach ($sxe->getChildren() as $element=>$value) {
                echo $value->species . '<br />';
            }
        }
    }
}
catch(Exception $e) {
    echo $e->getMessage();
}