PHP DOM replace element with a new element

前端 未结 1 1289
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-09 08:47

I have a DOM object with loaded HTML markup. I\'m trying to replace all embed tags that look like this:



        
相关标签:
1条回答
  • 2020-12-09 09:34

    It's easy to find elements from a DOM using getElementsByTagName. Indeed you wouldn't want to go near regular expressions for this.

    If the DOM you are talking about is a PHP DOMDocument, you'd do something like:

    $embeds= $document->getElementsByTagName('embed');
    foreach ($embeds as $embed) {
        $src= $embed->getAttribute('src');
        $width= $embed->getAttribute('width');
        $height= $embed->getAttribute('height');
    
        $link= $document->createElement('a');
        $link->setAttribute('class', 'player');
        $link->setAttribute('href', $src);
        $link->setAttribute('style', "display: block; width: {$width}px; height: {$height}px;");
    
        $embed->parentNode->replaceChild($link, $embed);
    }
    

    Edit re edit:

    $dom->replaceChild($e, $a); // this line doesn't work
    

    Yeah, replaceChild takes the new element to replace-with as the first argument and the child to-be-replaced as the second. This is not the way round you might expect, but it is consistent with all the other DOM methods. Also it's a method of the parent node of the child to be replaced.

    (I used class not id, as you can't have multiple elements on the same page all called id="player".)

    0 讨论(0)
提交回复
热议问题