foreach($links as $link_content)
{
$handle = curl_init(LINK_BASE.$link_content);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode != 200)
continue; //if not, go to next link
}我需要分析350个链接,并检查它们是否每个都可用(返回HTTP代码200)。目前我使用上面写的代码。不幸的是,这个操作需要很长的时间-超过2-4分钟。我必须以最快的方式检查每个链接。你能给我一些建议吗?
发布于 2015-01-09 04:57:14
我要说的是,您只需使用CURLOPT_NOBODY发出HTTP HEAD请求,而不是像您当前所做的那样,拉入整个内容。这段代码如下所示:
foreach($links as $link_content)
{
$handle = curl_init(LINK_BASE.$link_content);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_NOBODY, TRUE); // make HEAD
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode != 200)
continue; //if not, go to next link
}如果这不能像预期的那样减少时间,您还可以考虑使用curl_multi功能来并行化您的请求。您可以随意查看我创建的一个简单的基于curl的REST类,以获得一些关于如何执行curl_multi的更好的示例。欢迎您自由使用这个类- https://github.com/mikecbrant/php-rest-client
发布于 2015-01-09 05:02:24
您可以单独启动此PHP代码的多个实例。想象一下,在10个并行实例的情况下,时间会有多快!
按如下方式创建crawler.php文件:
<?php
$fileName = argv[1];
$fh = fopen($fileName, "r");
while($link_content = fgets($fh) !== FALSE) {
$handle = curl_init(LINK_BASE.$link_content);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
if($httpCode != 200) {
// log/output the bad URL
}
}
?>创建一个bat文件crawler.bat (如果你在Windows下),并放入以下代码:
php PathToCrawler/crawler.php %1现在您必须将您的URLS分发到不同的文件中,并使用控制台依次启动此bat:
crawler.bat UrlFileFrom1TO100.txt
crawler.bat UrlFileFrom101TO200.txt
crawler.bat UrlFileFrom201TO300.txt
crawler.bat UrlFileFrom301TO400.txt
...https://stackoverflow.com/questions/27849345
复制相似问题