2017-06-06 105 views
1

我试图从XML文件中提取数据(文件格式不受修改)。 XML数据包含HTML标签形式的内容和附件信息,这些信息令我感到悲伤。该XML的相关部分看起来是这样的:使用PHP/SimpleXML从XML中提取HTML

<item> 
    <p>Some text</p> 
    <p> Some more text</p> 
    <p><i>This</i> is important text.</p> 
</item> 

我需要的节点的内容,作为一个字符串(后插入DB)。该文本始终包裹在< p>标签,所以我尽量遍历这些,使用此代码:

$namediscussion = ''; 

foreach($sectionxml->xpath('//p') as $p) 
{ 
    $namediscussion = $namediscussion . $p . '</br>'; 

} 

echo $namediscussion 

($ sectionxml是ximplexml_load_string的输出()从父节点)。

的问题是,当我回声$ namediscussion,我得到的是:

Some text 
Some more text 
is important text. 

注意失踪词是斜体。我如何保留这个?我宁愿使用SimpleXML,但如果我必须去DOM,那也没关系。即使直接字符串操作也可以,但我似乎无法从SimpleXML节点中提取整个字符串。

非常感谢。

回答

1

您是铸造simplexmlelement,并且在这里simplexmlelement::__toString

Does not return text content that is inside this element's children. 

解释要解决缺少的话,这将丢弃元素孩子的内容,您可以使用simplexmlelement::asXML而不是投串如下图所示

$namediscussion = $namediscussion . strip_tags($p->asXML()) . '</br>'; 
+0

这个技巧!谢谢! – jgalak