1

指定された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 のルート ノードを選択する方法

Ps。HTMLの管理に正規表現を使用することはありません。

4

1 に答える 1

5

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>
于 2013-09-12T08:15:52.797 に答える