我想制作将一些属性添加到给定 html 的根标签的函数。
我正在这样做:
$dom = new 'DOMDocument();
$dom->loadHTML($content);
$root = $dom->documentElement;
$root->setAttribute("data-custom","true");
而对于$content='<h1 class="no-margin">Lorem</h1>'
它返回:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html data-custom="true"><body><h1 class="no-margin">Do more tomorrow. For less.</h1></body></html>
虽然应该只是:
<h1 data-custom="true" class="no-margin">Lorem</h1>
如何使 DOMDocument 不创建文档类型、html、body 标签,而只是对给定的 html 进行操作以及如何选择给定 html 的根节点
附言。我永远不会使用正则表达式来管理 html。
输出 HTML 时,请选择特定节点而不是整个文档:
<?php
$content = '<h1 class="no-margin">Lorem</h1>';
$dom = new 'DOMDocument();
$dom->loadHTML($content);
$node = $dom->getElementsByTagName('h1')->item(0);
$node->setAttribute('data-custom','true');
print $dom->saveHTML($node);
// <h1 class="no-margin" data-custom="true">Lorem</h1>
或者,由于格式正确,请将内容视为 XML 以避免添加额外的 HTML 标记:
<?php
$content = '<h1 class="no-margin">Lorem</h1>';
$dom = new 'DOMDocument();
$dom->loadXML($content);
$dom->documentElement->setAttribute('data-custom','true');
print $dom->saveXML($dom->documentElement);
// <h1 class="no-margin" data-custom="true">Lorem</h1>