I have the following HTML code:
我有以下HTML代码:
Some text
<h2>More text</h2>
<h2>Another h2</h2>
Before each H2 element I want to add a link (<a>
). I've been struggling with DOMdocument for a while, but I can't do so.
在每个H2元素之前,我想添加一个链接()。我一直在努力研究DOMdocument,但我不能这样做。
I've been struggling with a lot of variants here. Some crash, while the others add the link either at the beginning or the end of the document, or in the <H2>
element. None of them adds it before the <h2>
.
我一直在努力解决很多变种问题。有些崩溃,而其他人在文档的开头或结尾添加链接,或者在
元素中添加链接。他们都没有在
之前添加它。
$text = 'Some text<h2>More text</h2><h2>Another h2</h2>';
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($text);
$dom->preserveWhiteSpace = false;
$el = $dom->createElement('a');
$x = $dom->getElementsByTagName('h2')->item(0);
$dom->insertBefore($el,$x);
1 个解决方案
#1
3
You need to use insertBefore
on $tag->parentNode
. You also have to create a new element for every insert (or it'll move the old element).
您需要在$ tag-> parentNode上使用insertBefore。您还必须为每个插入创建一个新元素(或者它将移动旧元素)。
<?php
$text = 'Some text<h2>More text</h2><h2>Another h2</h2>';
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($text);
$dom->preserveWhiteSpace = false;
foreach ($dom->getElementsByTagName('h2') as $tag) {
$el = $dom->createElement('a');
$el->setAttribute('class', 'foo');
$el->setAttribute('href', '#');
$tag->parentNode->insertBefore($el, $tag);
}
foreach ($dom->getElementsByTagName('h3') as $tag) {
$el = $dom->createElement('a');
$el->setAttribute('class', 'foo');
$el->setAttribute('href', '#');
$tag->parentNode->insertBefore($el, $tag);
}
var_dump($dom->saveHTML());
Output:
输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>Some text</p>
<a class="foo" href="#"></a>
<h2>More text</h2>
<a class="foo" href="#"></a>
<h2>Another h2</h2>
</body>
</html>
DEMO
#1
3
You need to use insertBefore
on $tag->parentNode
. You also have to create a new element for every insert (or it'll move the old element).
您需要在$ tag-> parentNode上使用insertBefore。您还必须为每个插入创建一个新元素(或者它将移动旧元素)。
<?php
$text = 'Some text<h2>More text</h2><h2>Another h2</h2>';
$dom = new domDocument('1.0', 'utf-8');
$dom->loadHTML($text);
$dom->preserveWhiteSpace = false;
foreach ($dom->getElementsByTagName('h2') as $tag) {
$el = $dom->createElement('a');
$el->setAttribute('class', 'foo');
$el->setAttribute('href', '#');
$tag->parentNode->insertBefore($el, $tag);
}
foreach ($dom->getElementsByTagName('h3') as $tag) {
$el = $dom->createElement('a');
$el->setAttribute('class', 'foo');
$el->setAttribute('href', '#');
$tag->parentNode->insertBefore($el, $tag);
}
var_dump($dom->saveHTML());
Output:
输出:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<body>
<p>Some text</p>
<a class="foo" href="#"></a>
<h2>More text</h2>
<a class="foo" href="#"></a>
<h2>Another h2</h2>
</body>
</html>
DEMO