Twitter的REST API 1.0 user_timeline.json的替代品?

时间:2013-06-19 16:16:23

标签: php api twitter

我有一个文件使用user_timeline.json使用REST API 1.0基于用户的@handle来搜索Twitter搜索结果:

$json = file_get_contents("https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&screen_name=handle&count=25", TRUE);
$twitter_feed = json_decode($json, true);
foreach($twitter_feed as $tweet) {do something with $tweet}

由于REST API v1不再处于活动状态,因此我需要使用V1.1复制该过程。

我已阅读文档并了解我现在需要在运行此脚本之前进行身份验证。作为初学者,这个简单的剧本真的很吓人。

一旦经过身份验证,从某个用户返回一组推文的最佳方法是什么,这些推文将模仿上述内容并返回一个漂亮的json数组?

由于

2 个答案:

答案 0 :(得分:1)

看看:https://github.com/abraham/twitteroauth

使用这个库就可以了:

$twitterConnection = new TwitterOAuth(
    'COMSUMER KEY', // Consumer Key
    'CONSUMER SECRET',     // Consumer secret
    'ACCESS TOKEN',       // Access token
    'ACCESS TOKEN SECRET'      // Access token secret
);

$twitterData = $twitterConnection->get(
    'statuses/user_timeline',
    array(
        'screen_name'     => 'USERNAME',
        'count' => 3
    )
);

这将返回类似于V1.0 API的推文数组。

您可以在此处创建应用并获取所需的凭据:https://dev.twitter.com/apps

答案 1 :(得分:0)

<?php
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "xxx",  // Access token
'oauth_access_token_secret' => "xxx", // Access token secret
'consumer_key' => "xxx",  // Consumer Key
'consumer_secret' => "xxx" // Consumer secret
);

/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$requestMethod = "GET";
if (isset($_GET['user']))  {
    $user = $_GET['user'];
} else {
        $user  = "USERNAME"; /* USERNAME */
}
if (isset($_GET['count'])) {
    $user = $_GET['count'];
} else {
    $count = 20;
}

$getfield = "?screen_name=$user&count=$count";
$twitter = new TwitterAPIExchange($settings);
$string = json_decode($twitter  ->setGetfield($getfield)
                                ->buildOauth($url, $requestMethod)
                                ->performRequest(),$assoc = TRUE);

if($string["errors"][0]["message"] != "") {
    echo "<h3>Sorry, there was a problem.</h3><p>Twitter returned the following error message:</p><p><em>".$string[errors][0]["message"]."</em></p>";
    exit();
}
foreach($string as $items){

        echo "Time and Date of Tweet: ".$items['created_at']."<br />";
        echo "Tweet: ". $items['text']."<br />";
        echo "Tweeted by: ". $items['user']['name']."<br />";
        echo "Screen name: ". $items['user']['screen_name']."<br />";
        echo "Followers: ". $items['user']['followers_count']."<br />";
        echo "Friends: ". $items['user']['friends_count']."<br />";
        echo "Listed: ". $items['user']['listed_count']."<br /><hr />";
    }
?>