Question

I have the following HTML code:

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.

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);
Was it helpful?

Solution

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).

<?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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top