2011-01-31 6 views
0

DOM을 사용하여 PHP 이미지를 자동 크기 조정하는 PHP 스크립트를 만듭니다. 스크립트는 작동하지만 라이트 박스에 정상 크기를 표시하기 위해 <a ...></a> 사이의 크기 조정 된 이미지를 캡슐화하려고 할 때 문제가 발생합니다.PHP를 사용하여 요소에 링크 추가 DOM DOM

문제는 크기가 조정 된 이미지가 올바른 위치가 아닌 $ 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); 
} 
} 

감사 :

여기 내 코드입니다!

답변

2

대신 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); 
    } 
} 
+0

감사 작동 많이! 나는이 두 줄을 이전에 시도했지만, 잘못된 순서로 (나는 정말로 가깝다)주의를 기울였다. 고맙습니다 ! – SuN

+1

@sun'$ image'가'$ Zoom'에 추가 했으므로'$ image'가 올바른'parentNode'를 가지고 있지 않기 때문에 작동하지 않을 것입니다. 도와 줘서 기뻐요! – lonesomeday

관련 문제