通过 CURL 循环查询链接并在 PHP 中合并结果数组

发布于 2024-11-06 19:21:26 字数 1074 浏览 0 评论 0原文

下面的代码应该在 twitter 上搜索一个术语,循环遍历所有结果页面并返回一个大数组,并在每一步附加每个页面的结果。

foreach($search_terms as $term){
    //populate the obj array by going through all pages

    //set up connection
    $ch = curl_init();

    // go through all pages and save in an object array
    for($j=1; $j<16;$j++){
        $url ='http://search.twitter.com/search.json?q=' . $term .'&rpp=100&page='.$j.'';
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
        $var[$j] = curl_exec($ch);
        curl_close($ch);
        $obj = array_merge((array)$obj,(array)json_decode($var[$j], true));
    }
}

但它不太有效,并且出现以下错误:

curl_setopt(): 3 is not a valid cURL handle resource
curl_exec(): 3 is not a valid cURL handle resource
curl_close(): 3 is not a valid cURL handle resource
...... and this is repeated all the way from 3-> 7...
curl_setopt(): 7 is not a valid cURL handle resource
curl_exec(): 7 is not a valid cURL handle resource
curl_close(): 7 is not a valid cURL handle resource

The following code is supposed to search for a term on twitter, loop through all the result pages and return one big array with the results from each page appended at each step.

foreach($search_terms as $term){
    //populate the obj array by going through all pages

    //set up connection
    $ch = curl_init();

    // go through all pages and save in an object array
    for($j=1; $j<16;$j++){
        $url ='http://search.twitter.com/search.json?q=' . $term .'&rpp=100&page='.$j.'';
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); 
        $var[$j] = curl_exec($ch);
        curl_close($ch);
        $obj = array_merge((array)$obj,(array)json_decode($var[$j], true));
    }
}

It doesn't quite work though and am getting these errors:

curl_setopt(): 3 is not a valid cURL handle resource
curl_exec(): 3 is not a valid cURL handle resource
curl_close(): 3 is not a valid cURL handle resource
...... and this is repeated all the way from 3-> 7...
curl_setopt(): 7 is not a valid cURL handle resource
curl_exec(): 7 is not a valid cURL handle resource
curl_close(): 7 is not a valid cURL handle resource

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

爺獨霸怡葒院 2024-11-13 19:21:26
//set up connection
$ch = curl_init();
// go through all pages and save in an object array

for($j=1; $j<16;$j++){

您需要在循环内调用curl_init(),因为您在每次迭代结束时关闭它。

//set up connection
$ch = curl_init();
// go through all pages and save in an object array

for($j=1; $j<16;$j++){

You need the call to curl_init() inside your loop since you close it at the end of each iteration.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文