对于我正在构建的系统,我正在定义存储在 LINKSTYLE
中的通用 style
,该样式应应用于尚未应用的 a
元素样式(内联)。我对 DOMDocument
或 xpath
不太有经验,我不知道出了什么问题。
感谢戈登,我更新了我的代码:
libxml_use_internal_errors(true);
$html = '<a href="#">test</a>'.
'<a href="#" style="border:1px solid #000;">test2</a>';
$dom = new DOMDocument();
$dom->loadHtml($html);
$dom->normalizeDocument();
$xpath = new DOMXPath($dom);
foreach($xpath->query('//a[not(@style)]') as $node)
$node->setAttribute('style','border:1px solid #000');
return $html;
使用此更新代码,我不再收到错误,但 a
元素未设置样式。
最佳答案
使用libxml_use_internal_errors(true)
来抑制由loadHTML
引起的解析错误。
XPath 查询无效,因为 contains
需要在 style 属性中搜索一个值。
如果你想找到所有没有样式元素的 anchor ,只需使用
//a[not(@style)]
您没有看到您的更改,因为您正在返回存储在 $html 中的字符串。使用 DOMDocument 加载字符串后,必须在运行查询并修改 DOMDocument 该字符串的内部表示后将其序列化回来。
示例 ( demo )
$html = <<< HTML
<ul>
<li><a href="#foo" style="font-weight:bold">foo</a></li>
<li><a href="#bar">bar</a></li>
<li><a href="#baz">baz</a></li>
</ul>
HTML;
$dom = new DOMDocument;
$dom->loadHTML($html);
$xp = new DOMXpath($dom);
foreach ($xp->query('//a[not(@style)]') as $node) {
$node->setAttribute('style', 'font-weight:bold');
}
echo $dom->saveHTML($dom->getElementsByTagName('ul')->item(0));
输出:
<ul>
<li><a href="#foo" style="font-weight:bold">foo</a></li>
<li><a href="#bar" style="font-weight:bold">bar</a></li>
<li><a href="#baz" style="font-weight:bold">baz</a></li>
</ul>
请注意,为了使用 saveHTML
with an argument, you need at least PHP 5.3.6.
关于php - 使用 DOM 和 xpath 设置无样式链接的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6423079/