问题
I am using the html DOMDocument to find all instances of iFrames w/in a $content variable. I am able to output an image for each instance but would rather replace the iframe with the image and then save back to the content variable. Instead of echoing my result I would like to replace the current iframe. How do I do this?
$count = 1;
$dom = new DOMDocument;
$dom->loadHTML($content);
$iframes = $dom->getElementsByTagName('iframe');
foreach ($iframes as $iframe) {
echo "<img class='iframe-".self::return_video_type($iframe->getAttribute('src'))." iframe-ondemand-placeholderImg iframe-".$count."' src='" .$placeholder_image. "' height='".$iframe->getAttribute('height')."' width='" .$iframe->getAttribute('width'). "' data-iframe-src='" .$iframe->getAttribute('src'). "' /><br />";
$count++;
}
$content = $dom->saveHTML();
return $content;
回答1:
public DOMNode DOMNode::replaceChild ( DOMNode $newnode , DOMNode $oldnode )
http://php.net/manual/en/domnode.replacechild.php
Something like this:
$iframes = $dom->getElementsByTagName('iframe');
$i = $iframes->length - 1;
while ($i > -1) {
$iframe = $iframes->item($i);
$ignore = false;
$img = $dom->createElement("img");
$img->setAttribute("src",$iframe->getAttribute('src'));
$iframe->parentNode->replaceChild($img, $iframe);
$i--;
}
来源:https://stackoverflow.com/questions/28118437/parse-html-with-htmldom-replace-all-iframe-tags-with-another