gpt4 book ai didi

PHP DOM 用新元素替换元素

转载 作者:IT王子 更新时间:2023-10-28 23:52:29 25 4
gpt4 key购买 nike

我有一个加载了 HTML 标记的 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
}

最佳答案

使用 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" .)

关于PHP DOM 用新元素替换元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3194875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com