Добавить ссылку на элемент с PHP DOM - PullRequest
1 голос
/ 31 января 2011

Я делаю PHP-скрипт, использующий DOM для автоматического изменения размера изображений на лету.Сценарий работает, но у меня проблема, когда я пытаюсь инкапсулировать изображение с измененным размером между <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);
}
}

спасибо за помощь!

1 Ответ

3 голосов
/ 31 января 2011

Вы должны сделать это с помощью 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);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...