views:

473

answers:

2

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?

A: 
foreach($this->xml->xpath('/node/child') as $child){
   ...
}
Jayrox
Doesn't seem to work here.
strager
@Jayrox, It returns the <child> nodes but not the requested "This is", "some", and "text" nodes.
strager
Yeah it's those text nodes that I want, in the correct order with the child elements. Child elements are easy: foreach ($xml->children() as $child) { ... }
Jordie
+3  A: 

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";
    }
}
nickf
You get my upvote on that question. I'm scratching my head. People don't know that's valid XML? WTF?
Jordie
yeah, it made me stop and look at it again just to make sure...
nickf