DOMDocument :: loadHTML():warning - htmlParseEntityRef:实体中没有名称

Dav*_*ard 12 php warnings domdocument

我发现了几个类似的问题,但到目前为止,没有人能够帮助我.

我试图在HTML块中输出所有图像的'src',所以我正在使用DOMDocument().这种方法非常有效,但我在某些页面上收到警告,我无法弄清楚原因.有些帖子建议压制警告,但我更愿意找出警告产生的原因.

警告:DOMDocument :: loadHTML():htmlParseEntityRef:实体中没有名称,行:10

其中一个例子post->post_content就是产生错误 -

On Wednesday 21st November specialist rights of way solicitor Jonathan Cheal of Dyne Drewett will be speaking at the Annual Briefing for Rural Practice Surveyors and Agricultural Valuers in Petersfield.
<br>
Jonathan is one of many speakers during the day and he is specifically addressing issues of public rights of way and village greens.
<br>
Other speakers include:-
<br>
<ul>
<li>James Atrrill, Chairman of the Agricultural Valuers Associates of Hants, Wilts and Dorset;</li>
<li>Martin Lowry, Chairman of the RICS Countryside Policies Panel;</li>
<li>Angus Burnett, Director at Martin & Company;</li>
<li>Esther Smith, Partner at Thomas Eggar;</li>
<li>Jeremy Barrell, Barrell Tree Consultancy;</li>
<li>Robin Satow, Chairman of the RICS Surrey Local Association;</li>
<li>James Cooper, Stnsted Oark Foundation;</li>
<li>Fenella Collins, Head of Planning at the CLA; and</li>
<li>Tom Bodley, Partner at Batcheller Monkhouse</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

post->post_content如果有帮助的话,我可以发布更多包含内容的例子吗?

我暂时允许访问开发站点,因此您可以看到一些示例[注意 - 链接不再可访问,因为问题已得到解答] -

有关如何解决此问题的任何提示?谢谢.

$dom = new DOMDocument();
$dom->loadHTML(apply_filters('the_content', $post->post_content)); // Have tried stripping all tags but <img>, still generates warning
$nodes = $dom->getElementsByTagName('img');
foreach($nodes as $img) :
    $images[] = $img->getAttribute('src');
endforeach;
Run Code Online (Sandbox Code Playgroud)

Dav*_*ard 21

这个正确的答案来自@lonesomeday的评论.

我最好的猜测是在HTML中的某处有未转义的&符号(&).这将使解析器认为我们在实体引用中(例如©).当它到达时,它认为实体已经结束了.然后它实现它不符合实体的内容,因此它发出警告并以纯文本形式返回内容.

  • 那么我该如何解决呢?我不能在整个html字符串上调用htmlentities. (20认同)
  • @MavWolverine,我知道这是很多年后的事了,但我只是偶然发现了同样的问题。我发现的最简单的选择就是将“str_replace(' &amp; ', ' &amp; ', $string)”替换为“htmlentities”和“htmlspecialcharacters”,导致 HTML 标记的“&lt;”和“&gt;”被转换。现在我 100% 确定有一种更好的方法可以做到这一点,但这对我在一个简单的一次性解析工作中需要的内容进行了排序。 (5认同)
  • @PanPipes 有点限制性:`preg_replace("/&amp;(?!\S+;)/", "&amp;", $string)`。 (3认同)
  • 这节省了我的时间,我一直在努力,后来发现用户生成的内容在名称中包含 &amp; ,这是所有错误的根源。谢谢 (2认同)