Skip to content

Instantly share code, notes, and snippets.

@ArnaudLigny
Last active January 26, 2021 23:51
Show Gist options
  • Save ArnaudLigny/4677722 to your computer and use it in GitHub Desktop.
Save ArnaudLigny/4677722 to your computer and use it in GitHub Desktop.
PHP SPL SimpleXMLIterator examples
<?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();
}
<?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 {
$sxi = new SimpleXMLIterator($xmlstring);
$foo = $sxi->xpath('animal/category/species');
foreach ($foo as $k=>$v) {
echo $v . '<br />';
}
}
catch(Exception $e) {
echo $e->getMessage();
}
<?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>
@ArnaudLigny
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment