Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/276.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 在每个H2和H3之前添加元素_Php_Domdocument - Fatal编程技术网

Php 在每个H2和H3之前添加元素

Php 在每个H2和H3之前添加元素,php,domdocument,Php,Domdocument,我有以下HTML代码: Some text <h2>More text</h2> <h2>Another h2</h2> 一些文本 更多文本 另一个h2 在每个H2元素之前,我想添加一个链接()。我已经和DOMdocument斗争了一段时间,但我不能这么做 我一直在与很多变种抗争。有些崩溃,而另一些则在文档的开头或结尾或元素中添加链接。它们都没有将其添加到之前 $text='Some text更多text另一个h2'; $dom=新的domDo

我有以下HTML代码:

Some text
<h2>More text</h2>
<h2>Another h2</h2>
一些文本
更多文本
另一个h2
在每个H2元素之前,我想添加一个链接(
)。我已经和DOMdocument斗争了一段时间,但我不能这么做

我一直在与很多变种抗争。有些崩溃,而另一些则在文档的开头或结尾或
元素中添加链接。它们都没有将其添加到
之前

$text='Some text更多text另一个h2';
$dom=新的domDocument('1.0','utf-8');
$dom->loadHTML($text);
$dom->preserveWhiteSpace=false;
$el=$dom->createElement('a');
$x=$dom->getElementsByTagName('h2')->项(0);
$dom->insertBefore($el,$x);

您需要在
$tag->parentNode
上使用
insertBefore
。您还必须为每个插入创建一个新元素(否则它将移动旧元素)


我已经尝试过了,但我得到了以下错误
致命错误:未捕获的异常“DomeException”,消息为“Not Found error”
@Alex您总是有
h2
h3
元素吗?我有一个检查标记的条件。现在我正在测试我上面发布的HTML,所以这不是问题所在。@Alex在异常出现之前,
var\u dump($tag)
输出是什么?我们需要完整的、可测试的示例我添加了完整的示例。
$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);
<?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());
<!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>