1

我正在尝试使用 Twitter 搜索 API,我发现了一个 php 库,它使用纯应用身份验证进行身份验证,并向其中添加了 max_id 参数,但是,我想每 15 分钟运行 450 个查询(根据速率-limit),我不确定如何传递 max_id。所以我首先使用默认的 0 值运行它,然后它从 API 的响应中获取 max_id 结果并再次运行该函数,但这次使用检索到的 max_id 值并执行 450 次。我尝试了几件事,调用函数后可以得到max_id结果,但我不知道如何将其传回并告诉它以更新的值调用函数。

<?php

function search_for_a_term($bearer_token, $query, $result_type='mixed', $count='15', $max_id='0'){
    $url = "https://api.twitter.com/1.1/search/tweets.json"; // base url
    $q = $query; // query term

    $formed_url ='?q='.$q; // fully formed url
    if($result_type!='mixed'){$formed_url = $formed_url.'&result_type='.$result_type;} // result type - mixed(default), recent, popular
    if($count!='15'){$formed_url = $formed_url.'&count='.$count;} // results per page - defaulted to 15
    $formed_url = $formed_url.'&include_entities=true'; // makes sure the entities are included
    if($max_id!='0'){$formed_url=$formed_url.'&max_id='.$max_id;}
    $headers = array( 
        "GET /1.1/search/tweets.json".$formed_url." HTTP/1.1", 
        "Host: api.twitter.com", 
        "User-Agent: jonhurlock Twitter Application-only OAuth App v.1",
        "Authorization: Bearer ".$bearer_token."",
    );
    $ch = curl_init();  // setup a curl
    curl_setopt($ch, CURLOPT_URL,$url.$formed_url);  // set url to send to
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // set custom headers
    ob_start();  // start ouput buffering
    $output = curl_exec ($ch); // execute the curl
    $retrievedhtml = ob_get_contents(); // grab the retreived html
    ob_end_clean(); //End buffering and clean output 
    curl_close($ch); // close the curl
    $result= json_decode($retrievedhtml, true);
    return $result;
}

$results=search_for_a_term("mybearertoken", "mysearchterm");

/* would like to get all kinds of info from here and put it into a mysql database */

$max_id=$results["search_metadata"]["max_id_str"];
print $max_id; //this gives me the max_id for that page


?>

我知道必须有一些现有的库可以执行此操作,但我不能使用任何库,因为它们都还没有更新到仅应用程序身份验证。

编辑:我在脚本的开头放了一个循环,例如运行 3 次,然后放一个 print 语句来看看会发生什么,但它只打印出相同的 max_id,不访问三个不同的。

do{
$result = search_for_a_term("mybearertoken", "searchterm", $max_id);
 $max_id = $result["search_metadata"]["max_id_str"];
$i++;
print '    '.$max_id.'    ';
}while($i < 3);
4

0 回答 0