通过php从URL获取最大的图像

时间:2017-01-28 18:01:02

标签: php image

是否有可能找到我回来的最大图像。

这是我到目前为止的代码:

    <?php
$url="https://wikipedia.org/wiki/PHP";

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);

$tags = $doc->getElementsByTagName('img');

foreach ($tags as $tag) {
       echo $tag ->getAttribute('src');

}
?>

例如img 1:420x120px; img 2:1200x300px - &gt;输出链接URL来自img 2

2 个答案:

答案 0 :(得分:0)

您可以通过以下方式使用getimagesize()max(): -

$size_array = array(); // create an new empty array
foreach ($tags as $tag) {
       $size_array[getimagesize($tag ->getAttribute('src'))] = $tag ->getAttribute('src'); 

       //assign size as key and path as value to the newly created array
}
$max_size = max(array_keys($size_array)); // get max size from keys array
$max_file = $size_array[$max_size]; // find out file path based on max-size

注意: - 我假设$tag ->getAttribute('src')为您提供了图像文件的路径

答案 1 :(得分:0)

您可能想要创建一个包含所有width和相应height的摘要的数组,并对其进行排序:

foreach ($tags as $tag) {
    $array[] = [
        $tag->getAttribute('width') + $tag->getAttribute('height'),
        $tag->getAttribute('src')
    ];
}
array_multisort($array, SORT_DESC);
var_dump($array[0][1]);