【问题标题】:How get content of a node from a xml file with html tag included but as part of the content如何从包含 html 标记但作为内容的一部分的 xml 文件中获取节点的内容
【发布时间】:2017-03-25 13:22:41
【问题描述】:

有一个这样形成的 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,我可以使用什么查询来获取与 &lt;chapter id="1"&gt;...&lt;/chapter&gt; 关联的所有内容,其中包含 HTML 标记?输出如下:

<p>HTML content 1</p>
<q>HTML<q> content 2
HTML <b>content 3<b>

PS: 从注释中,我认为哪个问题提出了不同的问题。我只是问是否可能以及如何处理节点内的内容,如果不存在,则忽略 html-tag 修改原始 xml。

【问题讨论】:

标签: php xml


【解决方案1】:

您的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;
}

【讨论】:

  • 有一个问题,我不能修改原始文件。在上面的例子中,我已经复制了一个真实的情况,所以我需要像 il 文件给我数据一样工作。
  • 我已经更新了我的答案,请检查,现在符合您的要求
猜你喜欢
  • 1970-01-01
  • 2016-02-05
  • 2016-08-18
  • 1970-01-01
  • 2017-02-07
  • 2011-06-02
  • 2021-11-14
  • 1970-01-01
  • 2020-06-22
相关资源
最近更新 更多