我有一个函数,应该替换imgs:
$content = '<img width="500" height="500" src="hhhh.jpg" /> AWDEQWE ASdAa <p>sdasdasdas</p> <img width="500" height="500" src="hhhh.jpg" /> <p>awedaweq</p>';
$document = new DOMDocument;
$document->loadHTML($content);
$imgs= $document->getElementsByTagName('img');
foreach ($imgs as $img) {
$src= $img->getAttribute('src');
$width= $img->getAttribute('width');
$height= $img->getAttribute('height');
$link= $document->createElement('a');
$link->setAttribute('class', 'player');
$link->setAttribute('href', $src);
$link->setAttribute('style', "display: block; width: {$width}px; height: {$height}px;");
$img->parentNode->replaceChild($link, $img);
}
return $document->saveHTML();
它工作正常,但仅适用于第一张图片。 我的代码出了什么问题?
答案 0 :(得分:1)
replaceChild
方法调用将影响您正在迭代的实时nodeList,并实际从$imgs
中删除该节点。在这个突变之后,循环(即它下面的迭代器)失去了它在原始nodeList中的位置,因此循环退出。
解决方案是首先在标准数组中创建$imgs
的副本,并在其上创建循环:
foreach ($imgs as $img) {
$images[] = $img;
}
// now proceed with the loop you really want:
foreach ($images as $img) {
// ...etc
}
答案 1 :(得分:0)
您的问题在于计数器,访问DOMNode是动态的。你应该触摸柜台上方的dom元素。
$content = '<img width="400" height="400" src="asdf.jpg" /> AWDEQWE ASdAa <p>sdasdasdas</p> <img width="500" height="500" src="hhhh.jpg" /> <p>awedaweq</p>';
$document = new DOMDocument;
$document->loadHTML($content);
$imgs= $document->getElementsByTagName('img');
$i = $imgs->length - 1;
while ($i > -1)
{
$node = $imgs->item($i);
$link= $document->createElement('a');
$link->setAttribute('class', 'player');
$link->setAttribute('href', $node->getAttribute('src'));
$link->setAttribute('style', "display: block; width: {$node->getAttribute('width')}px; height: {$node->getAttribute('height')}px;");
$imgs->item($i)->parentNode->replaceChild($link, $node);
$i--;
}
var_dump($document->saveHTML());
答案 2 :(得分:0)
我这样解决了:
$document = new DOMDocument;
$document->loadHTML(mb_convert_encoding($content, 'HTML-ENTITIES', 'UTF-8'));;
$imgs = $document->getElementsByTagName('img');
$i = $imgs->length - 1;
while ($i > -1) {
$image = $imgs->item($i);
$ignore = false;
$width = $image->attributes->getNamedItem('width')->value;
$height = $image->attributes->getNamedItem('height')->value;
$src = $image->attributes->getNamedItem('src')->value;
$alt = $image->attributes->getNamedItem('alt')->value;
$class = $image->attributes->getNamedItem('class')->value;
$class = str_replace( array( "alignleft", "alignright" ), array( "amp_alignleft", "amp_alignright" ), $class );
$new_img = $document->createElement('amp-img', '');
$new_img->setAttribute('src', $src);
$new_img->setAttribute('class', $class);
$new_img->setAttribute('width', $width);
$new_img->setAttribute('height', $height);
$new_img->setAttribute('alt', $alt);
$new_img->setAttribute('layout', 'responsive');
$image->parentNode->replaceChild( $new_img, $image );
$i--;
}
return $document->saveHTML()