0

我有一个文件,它使用 REST API 1.0 使用 user_timeline.json 根据用户的@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 数组?

谢谢

4

2 回答 2

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

于 2013-06-19T16:27:34.210 回答
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 />";
    }
?>
于 2015-02-27T19:28:28.497 回答