2017-06-06 102 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