将更新后的值传递给函数(twitter api max_id问题)

时间:2013-04-29 14:25:42

标签: php function twitter

我正在尝试使用Twitter搜索API,我找到了一个使用app-only auth进行身份验证的php库,我添加了max_id参数,但是,我希望每15分钟运行450次查询(如根据速率限制)我不知道如何传递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


?>

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

编辑:我在脚本的开头放了一个循环来运行,例如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);

0 个答案:

没有答案