Automatically Adding Width And Height Attributes To Tags With A Php Function
Solution 1:
You're right about getimagesize()
. You can simply do something like this:
$img = 'image2.png';
$info = getimagesize($img);
printf('<img src="%s" %s>', $img, $info[3]);
If the image is hosted at a remote location, you'll have to download all the images though (the function takes care of it), so you might want to cache the result to speed things up on subsequent requests.
Edit: Just saw that you have a string containing various <img>
elements. This should do the trick:
<?php$html = <<<EOF
something <img src="https://www.google.com/images/logos/ssl_logo_lg.gif"> hello <img src="https://mail.google.com/mail/images/2/5/logo1.png">
EOF;
$dom = new DOMDocument();
$dom->loadHTML($html);
foreach ($dom->getElementsByTagName('img') as$img) {
list($width, $height) = getimagesize($img->getAttribute('src'));
$img->setAttribute('width', $width);
$img->setAttribute('height', $height);
}
$xpath = new DOMXpath($dom);
$newDom = new DOMDocument();
foreach ($xpath->query('//body/p')->item(0)->childNodes as$node) {
$newDom->appendChild($newDom->importNode($node, true));
}
$newHtml = $newDom->saveHTML();
?>
Solution 2:
The problem is that you are requiring the server to do an awful lot of work up front. I suspect it would be a lot more efficient to populate a database of sizes offline (or maintain a cache of sizes).
And having done this, you could push the work out to the browser by using a cacheable javascript which sets the image sizes and is called inline at the end of the html (which has the advantage the you don't need to push all the html through you PHP code for rewriting). Hint: iterate through document.images[]
HTH
C.
Solution 3:
you can use getimagesize() but it would be smart to store this information once and reuse it, or at least cache aggressively (as it's unlikely to change often) or your server will crawl to a halt with higher load
Post a Comment for "Automatically Adding Width And Height Attributes To Tags With A Php Function"