使用 PHP DOM 添加指向元素的链接

SuN*_*SuN 2 php dom

我使用 DOM 制作了一个 PHP 脚本来动态自动调整图像大小。该脚本有效,但当我尝试在<a ...>和之间封装调整大小的图像</a>(以在灯箱中显示正常大小)时,我遇到了问题。

问题是调整大小的图像显示在 $html 输出的末尾,这不是正确的位置。请问我做错了什么?

这是我的代码:

$dom = new DOMDocument();
@$dom->loadHTML($html);
$dom->preserveWhiteSpace = false;
$max_width = 530;

$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$img_width = $image->getAttribute('width');
$img_height = $image->getAttribute('height');

if($img_width > $max_width) {
    //Scale
    $scale_factor = $max_width/$img_width;
    $new_height = floor($img_height * $scale_factor);           
    //Set new attributes
    $image->setAttribute('width', $max_width);
    $image->setAttribute('height', $new_height);
    //Add Link
    $Zoom = $dom->createElement('a');
    $Zoom->setAttribute('class', 'zoom');
    $Zoom->setAttribute('href', $src);
    $dom->appendChild($Zoom);
    $Zoom->appendChild($image);
}
}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助 !

lon*_*day 5

你需要用以下方法来做到这replaceChild一点:

foreach ($images as $image) {
    $img_width = $image->getAttribute('width');
    $img_height = $image->getAttribute('height');

    if($img_width > $max_width) {
        //Scale
        $scale_factor = $max_width/$img_width;
        $new_height = floor($img_height * $scale_factor);           
        //Set new attributes
        $image->setAttribute('width', $max_width);
        $image->setAttribute('height', $new_height);
        //Add Link
        $Zoom = $dom->createElement('a');
        $Zoom->setAttribute('class', 'zoom');
        $Zoom->setAttribute('href', $src);

        $image->parentNode->replaceChild($Zoom, $image);
        $Zoom->appendChild($image);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @sun 那是行不通的,因为 `$image` 不会有正确的 `parentNode` 来工作,因为你将它附加到了 `$Zoom` 中。乐意效劳! (2认同)