SimpleXML access separated text nodes

余生长醉 提交于 2019-12-13 08:14:12

问题


I have an XML file like the following:

...
<MyElement>Introduction:<br />
   ...
</MyElement>
...

Are there any way to return "Introduction:" and the rest after </br> of that element?

I am using PHP and SimpleXML. Naively use echo $document->MyElement shows "Introduction:...", which mixed up the Introduction line and the content.


回答1:


SimpleXML does not have the concept of text-nodes as you might know it from DOMDocument (see as well with this comparison table).

So in PHP the option is that you import the <MyElement> element into DOM and you then do the operation there:

 # prints "Introduction:"

 echo dom_import_simplexml($myElement)->firstChild->data;
 //                                          ^      
 //                                          `- is DOMText



回答2:


to read your xml string use the following code, change root_element to match your root element name.

$content = simplexml_load_string($xml_string);
echo $content->root_element->MyElement


来源:https://stackoverflow.com/questions/17582470/simplexml-access-separated-text-nodes

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