如何从包含html标记但作为内容一部分的xml文件中获取节点的内容


How get content of a node from a xml file with html tag included but as part of the content

有这样一个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"> &lt;p&gt;HTML content 1&lt;/p&gt; </text>
  <text line="2"> &lt;q&gt;HTML&lt;q&gt; content 2 </text>
  <text line="3"> HTML &lt;b&gt;content 3&lt;b&gt; </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;
}