DOMDocument将属性添加到根标记

时间:2013-09-12 07:29:54

标签: php html dom domdocument

我想创建一些函数,为给定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不创建doctype,html,body标签,而只是对给定的html进行操作以及如何选择给定html的根节点

聚苯乙烯。我永远不会使用正则表达式来管理HTML。

1 个答案:

答案 0 :(得分:4)

输出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>
相关问题