PHP-获取其他网站内容并解析这些内容的最快方法


PHP - The fastest way to get content of another website and parse this content

我必须从网站上获取一些用户的参数。我可以这样做,因为每个用户都有一个唯一的ID,我可以通过URL:搜索用户

http://page.com/search_user.php?uid=X

所以我在for()循环中添加了这个URL,并尝试获得500个结果:

<?php
$start = time();
$results = array();
for($i=0; $i<= 500; $i++)
{
    $c = curl_init();
    curl_setopt($c, CURLOPT_URL, 'http://page.com/search_user.php?uid='.$i);
    curl_setopt($c, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 6.0; pl; rv:1.9.1.2) Gecko/20090729 desktopsmiley_2_2_5643778701369665_44_71 DS_gamingharbor Firefox/3.5.2 (.NET CLR 3.5.30729)');
    curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
    $p = curl_exec($c);
    curl_close($c);
    if ( preg_match('"<span class='"uname'">(.*?)</span>"si', $p, $matches) )
    {
        $username = $matches[1];
    }
    else
    {
        continue;
    }
    preg_match('"<table cellspacing='"0'">(.*?)</table>"si', $p, $matches);
    $comments = $matches[1];
    preg_match('"<tr class='"pos'">(.*?)</tr>"si', $comments, $matches_pos);
    preg_match_all('"<td>([0-9]+)</td>"si', $matches_pos[1], $matches);
    $comments_pos = $matches[1][2];
    preg_match('"<tr class='"neu'">(.*?)</tr>"si', $comments, $matches_neu);
    preg_match_all('"<td>([0-9]+)</td>"si', $matches_neu[1], $matches);
    $comments_neu = $matches[1][2];
    preg_match('"<tr class='"neg'">(.*?)</tr>"si', $comments, $matches_neg);
    preg_match_all('"<td>([0-9]+)</td>"si', $matches_neg[1], $matches);
    $comments_neg = $matches[1][2];
    $comments_all = $comments_pos+$comments_neu+$comments_neg;
    $about_me = 0;
    if ( preg_match('"<span>O mnie</span>"si', $p) )
    {
        $about_me = 1;
    }
    $results[] = array('comments' => $comments_all, 'about_me' => $about_me, 'username' => $username);
}
echo 'Generated in: <b>'.(time()-$start).'</b> seconds.<br><br>';
var_dump($results);
?>

最后我得到了结果:-所有内容都在135秒内生成。

然后我用file_get_contents()替换了curl,得到了:155秒。

得到这个结果的方法比旋度更快吗??我必须从另一个页面获得20.000000个结果,135秒对我来说太多了。

谢谢。

如果您真的需要查询不同的URL 500次,也许您应该考虑异步方法。上面的问题是,最慢的部分(瓶颈)是curl请求本身。在等待响应时,您的代码什么也不做。

试着看看带回调的PHP异步cURL(即,您将"几乎一次"发出500个请求,并在响应到来时异步处理)。

看看我之前关于如何划分和征服这类工作的回答。

调试长时间运行的PHP脚本

在你的情况下,我会说你遵循同样的想法,但你会进一步将请求分成500个一组。

相关文章: