Php DOMDocument将属性添加到根标记

Php DOMDocument将属性添加到根标记,php,html,dom,domdocument,Php,Html,Dom,Domdocument,我想创建一个函数,将一些属性添加到给定html的根标记中 我正在这样做: $dom = new \DOMDocument(); $dom->loadHTML($content); $root = $dom->documentElement; $root->setAttribute("data-custom","true"); 对于$content='Lorem' 它返回: <!DOCTYPE html PUBLIC "-//W3C//

我想创建一个函数,将一些属性添加到给定html的根标记中

我正在这样做:

    $dom = new \DOMDocument();
    $dom->loadHTML($content);

    $root = $dom->documentElement;

    $root->setAttribute("data-custom","true");
对于
$content='Lorem'

它返回:

<!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>
Lorem
如何使DOMDocument不创建doctype、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>

输出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>

好的,您已经讨论了根元素,并且还使用了
documentElement
——在HTML文档中是
HTML
。您应该考虑您试图实现的目标,并重新表述您的问题。您已经讨论了根元素,并且还使用了
documentElement
——对于HTML文档,它是
HTML
。你应该思考你想要达到的目标,并重新表述你的问题。