2010-07-07 163 views
16

我有一个加载了HTML标记的DOM对象。我试图取代,看起来像这一切嵌入标签:PHP DOM用新元素替换元素

<embed allowfullscreen="true" height="200" src="path/to/video/1.flv" width="320"></embed> 

有了这样的标签:

<a 
href="path/to/video/1.flv" 
style="display:block;width:320px;height:200px;" 
id="player"> 
</a> 

我有麻烦搞清楚了这一点,我不希望使用正则表达式。你能帮我吗?

编辑:

这是我到目前为止有:

  // 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 
     } 
+0

没有时间,现在写了一个答案,但检查出的http:/ /www.php.net/manual/en/class.domdocument.php – 2010-07-07 13:09:11

+0

我看了,但我无法弄清楚。我已经用我已经有的代码更新了我的答案,但是应该切换元素的最后一行不起作用。 – 2010-07-07 13:20:21

+0

查看类似的问题:http://stackoverflow.com/q/17864378 – 2013-07-25 22:48:45

回答

29

可以很容易地找到使用getElementsByTagName一个DOM元素。事实上,你不会想要为此接近正则表达式。

如果你正在谈论的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); 
} 

编辑重新编辑:

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

呀,replaceChild需要新元素来取代 - 作为第一个参数,将要替换的孩子作为第二个参数。这不是您可能期望的方式,但它与所有其他DOM方法一致。它也是要替换的子节点的父节点的一种方法。

(我用class没有id,因为你不能有相同的页面都称id="player"上的多个元素。)

+0

谢谢,下次我会知道:) – 2010-07-07 14:25:01