PHP DOM用新元素替换元素

Ric*_*nop 21 php dom

我有一个带有HTML标记的DOM对象.我正在尝试替换所有嵌入式标签,如下所示:

<embed allowfullscreen="true" height="200" src="path/to/video/1.flv" width="320"></embed>
Run Code Online (Sandbox Code Playgroud)

使用这样的标签:

<a 
href="path/to/video/1.flv" 
style="display:block;width:320px;height:200px;" 
id="player">
</a>
Run Code Online (Sandbox Code Playgroud)

我很难解决这个问题,我不想为此使用正则表达式.你能救我吗?

编辑:

这是我到目前为止:

         // DOM initialized above, not important
            foreach ($dom->getElementsByTagName('embed') as $e) {
                $path = $e->getAttribute('src');
          $width = $e->getAttribute('width') . 'px';
          $height = $e->getAttribute('height') . 'px';
          $a = $dom->createElement('a', '');
          $a->setAttribute('href', $path);
          $a->setAttribute('style', "display:block;width:$width;height:$height;");
          $a->setAttribute('id', 'player');
          $dom->replaceChild($e, $a); // this line doesn't work
      }
Run Code Online (Sandbox Code Playgroud)

bob*_*nce 36

使用DOM很容易找到DOM中的元素getElementsByTagName.事实上,你不想接近正则表达式.

如果您正在谈论的DOM是PHP DOMDocument,您可以执行以下操作:

$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);
}
Run Code Online (Sandbox Code Playgroud)

编辑重新编辑:

$dom->replaceChild($e, $a); // this line doesn't work
Run Code Online (Sandbox Code Playgroud)

是的,replaceChild将新元素替换为第一个参数,将要替换的子元素替换为第二个参数.这不是您可能期望的方式,但它与所有其他DOM方法一致.此外,它还是要替换子节点的父节点的方法.

(我class没有使用id,因为你不能在同一页面上调用多个元素id="player".)

  • “ _这也是要替换子节点的父节点的方法。_”-这结束了我40分钟的调试会话。谢谢! (2认同)
  • 如果您尝试在 foreach 循环中替换 DOM 元素,那么元素将被跳过,因为您正在更改“活动”对象。向后迭代、将节点列表转换为数组或使用基于节点列表长度的 while 循环是解决该问题的几种方法。 (2认同)