Add a link to an Element with PHP DOM
I make a PHP script using DOM to auto-resize th开发者_运维技巧e images on the fly. The script works but i have a problem when i try to encapsulate a resized image between <a ...>
and </a>
(to show the normal size in a lightbox).
Problem is resized images are shown at the end of the $html output, which is not the correct position. What am i doing wrong please ?
Here is my code :
$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);
}
}
thank for your help !
You need to do this with replaceChild
instead:
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);
}
}
精彩评论