4

What I want is a function I can run on user input that will intelligently find and add the width and height attributes to any <img> tag in a blob of HTML so as to avoid page-reflowing issues while images load.

I am writing the posting script for a PHP forum, where a user's input is sanitised and generally made nicer before writing it to the database for later display. As an example of what I do to make things nicer, I have a script that inserts alt attributes into images like so:

Here are two images: <img src="http://example.com/image.png"> <img src="http://example.com/image2.png">

which, upon sanitising by the posting script, becomes

Here are two images: <img src="http://example.com/image.png" alt="Posted image"> <img src="http://example.com/image2.png" alt="Posted image">

(This makes it validate under HTML 4 strict, but maybe isn't in the spirit of the alt attribute—alas!)

So, for my function, I have a vague idea that the server will need to run getimagesize() on each external image it finds in the block of HTML, then apply the attributes that function generates to each and every <img> tag it runs into. I assume that this function has been written before, but I have had no luck on Google or php.net docs. Do I have to start from scratch, or is somebody aware of a (relatively) robust function that I can use or adapt to do this job?

4

3 回答 3

6

你是对的getimagesize()。你可以简单地做这样的事情:

$img = 'image2.png';
$info = getimagesize($img);
printf('<img src="%s" %s>', $img, $info[3]);

如果图像托管在远程位置,则您必须下载所有图像(该功能负责处理它),因此您可能希望缓存结果以加快后续请求的速度。

编辑:刚刚看到你有一个包含各种<img>元素的字符串。这应该可以解决问题:

<?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();
?>
于 2010-07-01T12:11:08.020 回答
0

问题是您需要服务器预先完成大量工作。我怀疑离线填充大小数据库(或维护大小缓存)会更有效。

完成此操作后,您可以使用可缓存的 javascript 将工作推送到浏览器,该 javascript 设置图像大小并在 html 末尾被内联调用(其优点是您不需要推送所有 html通过你的 PHP 代码进行重写)。提示:遍历 document.images[]

高温高压

C。

于 2010-07-01T12:15:27.920 回答
0

您可以使用 getimagesize() 但将这些信息存储一次并重新使用它会很聪明,或者至少积极缓存(因为它不太可能经常更改),否则您的服务器将在更高的负载下爬行

于 2010-07-01T12:16:59.687 回答