我尝试将一些 html 加载到 DOMDocument php 对象。但它无法加载具有属性 href 且其中包含 & 符号的 anchor 元素。 这是要加载的 html 代码:
<p>Jaźń</p>
<p>gęślą<a href="http://example.com/?abc&def">zażółć</a></p>
<p>Hello!</p>
如您所见,在 url 的查询字符串中,abc
和 def
之间有一个符号。它是 utf-8 文本。
将其加载到 DOMDocument 会导致警告,除非删除了 & 符号。警告是
Warning: DOMDocument::loadHTML(): htmlParseEntityRef: expecting ';' in Entity, line: 2 in /in/MXN5X on line 8
在我的 phpunit 中它会导致错误。
代码是这样的:
<?php
$html = <<< 'WOW'
<p>Jaźń</p>
<p>gęślą<a href="http://example.com/?abc&def">zażółć</a></p>
<p>Hello!</p>
WOW;
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8"), LIBXML_HTML_NODEFDTD);
如何将带有 & 符号的 anchor 元素加载到 DOMDocument 对象?
最佳答案
我遇到了同样的问题。你应该使用 &
而不是 & 并且它运行良好......
关于php - anchor 元素和 UTF-8 的 href 属性中 DOMDocument 中的 & 符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38495286/