有这样一个xml文件:
<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>
使用DOMDocument,我可以使用什么查询来获取与包含HTML标记的<chapter id="1">...</chapter>
相关的所有内容?
<p>HTML content 1</p>
<q>HTML<q> content 2
HTML <b>content 3<b>
PS:从笔记上看,我认为哪个问题问的有些不同。只是我问是否可能,以及如何处理节点内的内容忽略html标记,如果不可能修改原始xml
您的xml字符串无效,您必须首先将text
节点中的content
转换为htmlEntities,例如:
$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字符串,则需要使用regex而不是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;
}
标题>