【发布时间】:2019-09-09 23:59:54
【问题描述】:
将图像作为数组获取时遇到以下问题。
在这段代码中,我试图检查搜索图像是否存在 Test 1 - 如果存在,则显示,如果不存在,则尝试使用 Test 2 就是这样。当前的代码可以做到,但速度非常慢。
这个if (sizeof($matches[1]) > 3) { 因为这个3 有时会在被抓取的网站上包含广告,所以这是我安全的跳过它的方法。
我的问题是如何加快下面的代码以更快地获得if (sizeof($matches[1]) > 3) {?我相信这会让代码变得很慢,因为这个数组可能包含多达 1000 张图片
$get_search = 'Test 1';
$html = file_get_contents('https://www.everypixel.com/search?q='.$get_search.'&is_id=1&st=free');
preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $html, $matches);
if (sizeof($matches[1]) > 3) {
$ch_foreach = 1;
}
if ($ch_foreach == 0) {
$get_search = 'Test 2';
$html = file_get_contents('https://www.everypixel.com/search?q='.$get_search.'&is_id=1&st=free');
preg_match_all('|<img.*?src=[\'"](.*?)[\'"].*?>|i', $html, $matches);
if (sizeof($matches[1]) > 3) {
$ch_foreach = 1;
}
}
foreach ($matches[1] as $match) if ($tmp++ < 20) {
if (@getimagesize($match)) {
// display image
echo $match;
}
}
【问题讨论】:
-
你错了,这里检查数组的大小不是性能问题,
$ch_foreach = 1;也不是性能问题。这段代码可能比较慢的部分是 HTTP 获取和正则表达式执行。要优化 http 获取,切换到 curl 并使用 CURLOPT_ENCODING(甚至更快,使用更新守护进程实现本地缓存),并优化 html 解析,切换到使用 DOMDocument 和 DOMXPath 解析,而不是使用正则表达式解析。
标签: php curl file-get-contents