你的XML字符串無效,則必須在text
節點轉換content
到ヶ輛第一,例如:
$textContent = htmlentities($text);
在那之後,我們有:
$xmlText = '<chapter id="1">
<text line="1"> <p>HTML content 1</p> </text>
<text line="2"> <q>HTML<q> content 2 </text>
<text line="3"> HTML <b>content 3<b> </text>
</chapter>';
現在,我們只需要請使用SimpleXMLElement
來解析:
$xmlObject = new SimpleXMLElement($xmlText);
$items = $xmlObject->xpath("text");
foreach ($items as $item){
echo html_entity_decode($item);
}
更新1
如果你不能改變你的XML字符串,你需要使用正則表達式,而不是htmlDom:
function get_tag_contents($tag, $xml) {
preg_match_all("#<$tag .*?>(.*?)</$tag>#", $xml, $matches);
return $matches[1];
}
$invalidXml = '<chapter id="1">
<text line="1"> <p>HTML content 1</p> </text>
<text line="2"> <q>HTML<q> content 2 </text>
<text line="3"> HTML <b>content 3<b> </text>
</chapter>';
$textContents = get_tag_contents('text', $invalidXml);
foreach ($textContents as $content) {
echo $content;
}
[您如何分析和處理HTML/XML的可能的複製在PHP?](http://stackoverflow.com/questions/3577641/how-do-you-parse-and-process-html-xml-in-php) – RST