简体   繁体   中英

Change outerHTML of a php DOMElement?

How do I change the outerHtml of an element using PHP DomDocument class? Make sure, no third party library is used such as Simple PHP Dom or else.

For example: I want to do something like this.

$dom = new DOMDocument;
$dom->loadHTML($html);  
$tag = $dom->getElementsByTagName('h3');
foreach ($tag as $e) {
 $e->outerHTML = '<h5>Hello World</h5>';
}

libxml_clear_errors();
$html = $dom->saveHTML();
echo $html;

And the output should be like this:

Old Output: <h3>Hello World</h3>
But I need this new output: <p>Hello World</p>

You can create a copy of the element content and attributes in a new node (with the new name you need), and use the function replaceChild() .

The current code will work only with simple elements (a text inside a node), if you have nested elements, you will need to write a recursive function.

$dom = new DOMDocument;
$dom->loadHTML($html);  

$titles = $dom->getElementsByTagName('h3');
for($i = $titles->length-1 ; $i >= 0 ; $i--)
{
    $title = $titles->item($i);
    $titleText = $title->textContent ; // get original content of the node

    $newTitle = $dom->createElement('h5'); // create a new node with the correct name
    $newTitle->textContent = $titleText ; // copy the content of the original node

    // copy the attribute (class, style, ...)
    $attributes = $title->attributes ;
    for($j = $attributes->length-1 ; $j>= 0 ; --$j)
    {
        $attributeName = $attributes->item($j)->nodeName ;
        $attributeValue = $attributes->item($j)->nodeValue ;

        $newAttribute = $dom->createAttribute($attributeName);
        $newAttribute->nodeValue = $attributeValue ;

        $newTitle->appendChild($newAttribute);
    }


    $title->parentNode->replaceChild($newTitle, $title); // replace original node per our copy
}


libxml_clear_errors();
$html = $dom->saveHTML();
echo $html;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM