PHP Twitter API搜索/tweets仅从上一小时获取tweets [英] PHP Twitter API search/tweets GET tweets from last hour ONLY

查看:81
本文介绍了PHP Twitter API搜索/tweets仅从上一小时获取tweets的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Internet上四处逛逛,还没有找到解决方案.我只想获取过去一个小时的带有特定标签的推文.

Hi I have been looking around on the internet and haven't been able to find a solution yet. I want to only get the tweets from the past hour which have a certain hashtag.

我正在使用该标签添加推文,但我不知道如何仅获取过去一个小时的推文.

I am pulling the tweets in with that hashtag but I dont know how to only get the ones from the past hour.

以下是一些示例数据:

您可以看到那里有一个created_at日期,但是我不知道如何使用它来获取过去一个小时的日期.我认为这将是我能够做到的唯一方法.

As you can see there is a created_at date there but I dont know how to use this to get the ones from the past hour. I think this would be the only way that I would be able to do it.

我想到的最好的方法是将该日期转换为UNIX时间戳,然后检查它是否是最后一个小时的推文.但是有很多数据要经过,这似乎不是一个很好的解决方案,但我没想到.

The best way I can think of doing it is converting that date into a UNIX timestamp and then checking if it was tweets in the last hour. But there is a lot of data to go through and this doesnt seem like a very good solution but its all I cant think of.

如果这是唯一的解决方案,请问有人给我一个例子,说明如何将该日期转换为PHP中的UNIX时间戳.如果您有其他解决方案,我希望看到一个详细的示例:)谢谢

If that is the only solution there is, would some given me an example on how to convert that date to a UNIX timestamp in PHP. If you have a different solution I would love to see a detailed example :) Thanks

您可能还会发现此链接有用 https://developer.twitter.com/zh-CN/docs/tweets/search/api-reference/get-search-tweets

You may also find this link useful https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets

推荐答案

我也找不到替代解决方案,因此我对其进行了编码. WINDOW常数将时间间隔定义为1小时.希望对您有帮助!

I couldn't find an alternative solution neither so I coded it. The WINDOW constant defines the time interval to 1 hour. Hope it helps!

<?php
//Access token & access token secret
define("TOKEN", 'XXXXXXXXXXXXXXXX'); //Access token
define("TOKEN_SECRET", 'XXXXXXXXXXXXXXXX'); //Access token secret
//Consumer API keys
define("CONSUMER_KEY", 'XXXXXXXXXXXXXXXX'); //API key
define("CONSUMER_SECRET", 'XXXXXXXXXXXXXXXX'); //API secret key

$method='GET';
$host='api.twitter.com';
$path='/1.1/search/tweets.json'; //API call path
$url="https://$host$path";
//Query parameters
$query = array(
    'q' => 'wordtosearch',          /* Word to search */
    'count' => '100',               /* Specifies a maximum number of tweets you want to get back, up to 100. As you have 100 API calls per hour only, you want to max it */
    'result_type' => 'recent',      /* Return only the most recent results in the response */
    'include_entities' => 'false'   /* Saving unnecessary data */
);
//time window in hours
define("WINDOW", 1); 

//Authentication
$oauth = array(
    'oauth_consumer_key' => CONSUMER_KEY,
    'oauth_token' => TOKEN,
    'oauth_nonce' => (string)mt_rand(), //A stronger nonce is recommended
    'oauth_timestamp' => time(),
    'oauth_signature_method' => 'HMAC-SHA1',
    'oauth_version' => '1.0'
);
//Used in Twitter's demo
function add_quotes($str) { return '"'.$str.'"'; }

//Searchs Twitter for a word and get a couple of results
function twitter_search($query, $oauth, $url){  
    global $method; 

    $arr=array_merge($oauth, $query); //Combine the values THEN sort
    asort($arr); //Secondary sort (value)
    ksort($arr); //Primary sort (key)
    $querystring=http_build_query($arr,'','&');
    //Mash everything together for the text to hash
    $base_string=$method."&".rawurlencode($url)."&".rawurlencode($querystring);
    //Same with the key
    $key=rawurlencode(CONSUMER_SECRET)."&".rawurlencode(TOKEN_SECRET);
    //Generate the hash
    $signature=rawurlencode(base64_encode(hash_hmac('sha1', $base_string, $key, true)));
    //This time we're using a normal GET query, and we're only encoding the query params (without the oauth params)
    $url=str_replace("&amp;","&",$url."?".http_build_query($query));
    $oauth['oauth_signature'] = $signature; //Don't want to abandon all that work!
    ksort($oauth); //Probably not necessary, but twitter's demo does it
    $oauth=array_map("add_quotes", $oauth); //Also not necessary, but twitter's demo does this too  
    //This is the full value of the Authorization line
    $auth="OAuth ".urldecode(http_build_query($oauth, '', ', '));
    //If you're doing post, you need to skip the GET building above and instead supply query parameters to CURLOPT_POSTFIELDS
    $options=array( CURLOPT_HTTPHEADER => array("Authorization: $auth"),
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);
    //Query Twitter API
    $feed=curl_init();
    curl_setopt_array($feed, $options);
    $json=curl_exec($feed);
    curl_close($feed);
    //Return decoded response
    return json_decode($json);
};

//Initializing
$done = false;      //Loop flag
$countCalls=0;      //Api Calls
$countTweets=0;     //Tweets fetched
$intervalTweets=0;  //Tweets in the last WINDOW hour
$twitter_data = new stdClass();
$now=new DateTime(date('D M j H:i:s O Y')); //Current search time

//Fetching starts
do{
    $twitter_data = twitter_search($query,$oauth,$url);
    $countCalls+=1;
    //Partial results, updating the total amount of tweets fetched
    $countTweets += count($twitter_data->statuses);
    //Searching for tweets inside the time window
    foreach($twitter_data->statuses as $tweet){
        $time=new DateTime($tweet->created_at);
        $interval = $time->diff($now);      
        $days=$interval->format('%a');
        $hours=$interval->h;
        $mins=$interval->i;
        $secs=$interval->s;
        $diff=$days*24 + $hours + $mins/60 + $secs/3600;
        if($diff<WINDOW){
            $intervalTweets+=1;
        }else{
            $done = true;
            break;
        }               
    }       
    //If not all the tweets have been fetched, then redo... 
    if(!$done && isset($twitter_data->search_metadata->next_results)){      
        //Parsing information for max_id in tweets fetched
        $string="?max_id="; 
        $parse=explode("&",$twitter_data->search_metadata->next_results);       
        $maxID=substr($parse[0],strpos($parse[0],$string)+strlen($string));     
        $query['max_id'] = -1+$maxID; //Returns results with an ID less than (that is, older than) or equal to the specified ID, to avoid getting the same last tweet
        //Twitter will be queried again, this time with the addition of 'max_id'        
    }else{      
        $done = true;
    }   
}while(!$done);

//If all the tweets have been fetched, then we are done
echo "<p>query: ".urldecode($query['q'])."</p>";
echo "<p>tweets fetched: ".$countTweets."</p>";
echo "<p>API calls: ".$countCalls."</p>";
echo "<p>tweets in the last ".WINDOW." hour: ".$intervalTweets."</p>";
?>

这篇关于PHP Twitter API搜索/tweets仅从上一小时获取tweets的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆