How can I parse XML to get multiple text blocks with SimpleXML?

陌路散爱 提交于 2019-12-13 00:57:39

问题


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?


回答1:


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";
    }
}



回答2:


foreach($this->xml->xpath('/node/child') as $child){
   ...
}


来源:https://stackoverflow.com/questions/664202/how-can-i-parse-xml-to-get-multiple-text-blocks-with-simplexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!