使用 php 下载数千张图像,如何绕过空白图像

MSh*_*ack 2 php

我有一个 php 文件,它正在创建我要下载的图像的 url 路径列表。目前,我刚刚创建一个列表,将其复制并粘贴到桌面应用程序中,该应用程序将通过 txt 文件中的 url 列表下载图像。我想继续将下载添加到 php 文件中以绕过当前步骤。

目前,以下内容生成我用来复制并粘贴到桌面下载应用程序的网址列表

foreach ($espn_ar as $key => $value) echo 'ht'.'tps://a.espncdn.com/i/headshots/nfl/players/full/'.$espn_ar[$key].'.png<br>';
Run Code Online (Sandbox Code Playgroud)

生成的列表如下所示,包含大约 2500 个 url 路径

https://a.espncdn.com/i/headshots/nfl/players/full/2580.png
https://a.espncdn.com/i/headshots/nfl/players/full/2330.png
https://a.espncdn.com/i/headshots/nfl/players/full/2977742.png
https://a.espncdn.com/i/headshots/nfl/players/full/5528.png
https://a.espncdn.com/i/headshots/nfl/players/full/5529.png
https://a.espncdn.com/i/headshots/nfl/players/full/5536.png
https://a.espncdn.com/i/headshots/nfl/players/full/5713.png
https://a.espncdn.com/i/headshots/nfl/players/full/8439.png
https://a.espncdn.com/i/headshots/nfl/players/full/8461.png
https://a.espncdn.com/i/headshots/nfl/players/full/8479.png
Run Code Online (Sandbox Code Playgroud)

为了绕过复制和粘贴到桌面应用程序的步骤,我添加了以下内容

foreach ($espn_ar as $key => $value) {
    $url = 'ht' . 'tps://a.espncdn.com/i/headshots/nfl/players/full/' . $espn_ar[$key] . '.png';
    $img = 'images/' . $espn_ar[$key] . '.png';
    $ch = curl_init($url);
    $fp = fopen($img, 'wb');
    curl_setopt($ch, CURLOPT_FILE, $fp);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
}
Run Code Online (Sandbox Code Playgroud)

这似乎可以将所有图像下载到名为“images”的目录设置中

问题 1 - 我所做的是实现我想要实现的目标的最佳方法吗?

问题 2 - 使用桌面应用程序时,如果 url 路径不包含图像,则不会下载空白图像,但是使用 php 方法,如果其中一个 url 路径不包含任何图像,它会下载空白图像,那么我如何添加一些内容来不下载空白 png 文件,或者只下载超过 1kb 的文件,或者在下载所有文件后删除所有 1kb 或更小的文件,不知道处理该问题的最佳方法是什么。

shi*_*ngo 12

我所做的是实现我想要实现的目标的最佳方法吗?

此类问题的答案通常基于您对“最佳”的解释。既然你说你对 php 的了解很少,我只是猜你想要一个简单的方法,而我能找到的最简单的方法是:

file_put_contents($img, file_get_contents($url));
Run Code Online (Sandbox Code Playgroud)

请注意,您allow_url_fopen = On应该extension=opensslphp.ini.

这是一个完整的示例:

foreach ($espn_ar as $value) {
    $url = "https://a.espncdn.com/i/headshots/nfl/players/full/$value.png";
    $img = "images/$value.png";
    $content = file_get_contents($url);
    file_put_contents($img, $content);
}
Run Code Online (Sandbox Code Playgroud)

使用桌面应用程序时,如果 url 路径不包含图像,它不会下载空白图像,但是使用 php 方法,如果其中一个 url 路径不包含任何图像,它会下载空白图像,那么如何我可以添加一些内容来不下载空白 png 文件,或者只下载超过 1kb 的文件,或者在下载所有文件后删除所有 1kb 或更小的文件,不确定处理该问题的最佳方法是什么。

因为我无法检查所有的URL,我猜测这些空白图像可能是由404错误引起的,或者图像确实是空白的。我会检查所有的。

    $content = file_get_contents($url);
    
    # download failed
    if($content === false)
        continue;
    
    # 404 error
    if(strpos($http_response_header[0], '404 Not Found') !== false)
        continue;

    # size < 1kb
    if(strlen($content) < 1024)
        continue;

    file_put_contents($img, $content);
Run Code Online (Sandbox Code Playgroud)