Home>

I am trying DOM manipulation with php.

$dom = new DOMDocument ();
$dom->loadHTML ($content);
$divs = $dom->getElementsByTagName ('div');
foreach ($divs as $div):
    if ($div->hasAttribute ('class')&&preg_match ('/ target-class/i', $div->getAttribute ('class'))) (
        ----
    }
endforeach;
$dom->saveHTML ();


$content is

<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>
<div>hogehoge</div>

.

$content contents

<p><span>hogehoge</span></p>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<div>hogehoge</div>
<p><span>hogehoge</span></p>
<div>hogehoge</div>
<div>hogehoge</div>
<p><span>hogehoge</span></p>

How can I make it look like this?
I just want the div tag to have a different tag name.

Current method
$dom = new DOMDocument ();
$dom->loadHTML ($content);
$divs = $dom->getElementsByTagName ('div');
foreach ($divs as $div):
    if ($div->hasAttribute ('class')&&preg_match ('/ target-class/i', $div->getAttribute ('class'))) (
        $new_p = $dom->createElement ('p');
        // copy all attributes
        foreach ($div->attributes as $attr) {
            $new_p->setAttribute ($attr->nodeName, $attr->nodeValue);
        }
        $new_p_content = $div->nodeValue;
        $new_p->nodeValue = "<span class = \" target-class-inner \ ">{$new_p_content}</span>";
        $div->parentNode->replaceChild ($new_p, $div);
    }
endforeach;
return mb_convert_encoding ($dom->saveHTML (), 'UTF-8', 'HTML-ENTITIES');
php