2011-01-31 14 views
0

DOMを使用して画像をオンザフライで自動サイズ変更するPHPスクリプトを作成します。スクリプトは動作しますが、サイズ変更された画像を<a ...></a>の間にカプセル化しようとすると問題が発生します(ライトボックスでは通常のサイズを表示します)。PHPを使用して要素にリンクを追加する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

おかげで、それは作品がたくさん!私はちょうど私が前にこれらの2行を試したが、間違った順序で(私は本当に近い)気づいた。ありがとうございました ! – SuN

+1

@sun '$ image'が' $ Zoom'に追加されているので、 '$ image'が正しく' parentNode'を持っていなかったので動作しませんでした。助けてうれしい! – lonesomeday

関連する問題