How can I parse XML to get multiple text blocks with SimpleXML?
Question
I want to parse some XML that looks like this:
<node>
This is
<child>
blah
</child>
some
<child>
foo
</child>
text
</node>
How do I get access to the text node children in Simple XML?
Can I access them in the correct order of text and element children?
Do I need some other package for this?
Solution
I'd strongly recommend switching to the DOM functions over SimpleXML. I had an answer like this a while ago which wasn't very popular, but I still stand by it. The DOM functions are just so much powerful: the extra verbosity is worth it.
$doc = new DOMDocument();
$doc->loadXML($xmlString);
foreach ($doc->documentElement->childNodes as $node) {
if ($node->nodeType === XML_TEXT_NODE) {
echo $node->nodeValue . "\n";
}
}
OTHER TIPS
foreach($this->xml->xpath('/node/child') as $child){
...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow