由于Twitter API 1.0于2013年6月11日退休,下面的脚本不再工作。
// Create curl resource
$ch = curl_init();
// Set url
curl_setopt($ch, CURLOPT_URL, "http://twitter.com/statuses/user_timeline/myscreenname.json?count=10");
// Return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string
$output = curl_exec($ch);
// Close curl resource to free up system resources
curl_close($ch);
if ($output)
{
$tweets = json_decode($output,true);
foreach ($tweets as $tweet)
{
print_r($tweet);
}
}
如何用最少的代码获得user_timeline(最近的状态)?
我找到了这个:https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline
但是我得到了以下错误:
"{"errors":[{"message":"Could not authenticate you","code":32}]}"
有很多课程,但在尝试了几个之后,它们似乎都没有工作,因为Twitter上的这些更新,加上其中一些是非常高级的课程,有很多功能,我真的不需要。
用PHP获取最近用户状态的最简单/最短的方法是什么?
访问dev.twitter.com并创建一个应用程序。这将为您提供所需的证书。下面是我最近用PHP和cURL编写的一个实现。
<?php
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "YOURVALUE";
$oauth_access_token_secret = "YOURVALUE";
$consumer_key = "YOURVALUE";
$consumer_secret = "YOURVALUE";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// Make requests
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
//print it out
print_r ($twitter_data);
?>
这可以从命令行运行:
$ php <name of PHP script>.php
Rivers粘贴的代码很棒。非常感谢!我是新来的,不能评论,我只想回答来自javiervd的问题(你如何设置screen_name和这种方法的计数?),因为我已经浪费了很多时间来弄清楚。
您需要将参数添加到URL和签名创建过程中。
创建签名是一篇帮助我的文章。这是我的代码:
$oauth = array(
'screen_name' => 'DwightHoward',
'count' => 2,
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
$options = array(
CURLOPT_HTTPHEADER => $header,
//CURLOPT_POSTFIELDS => $postfields,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?screen_name=DwightHoward&count=2',
CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false
);
下面是一个简单的从你的时间轴上获得指定数量的推文的方法。它的功能与其他示例基本相同,只是使用了更少的代码。
只需填写键和调整$count到您的喜欢:
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json';
$count = '10';
$oauth = array('count' => $count,
'oauth_consumer_key' => '[CONSUMER KEY]',
'oauth_nonce' => md5(mt_rand()),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_timestamp' => time(),
'oauth_token' => '[ACCESS TOKEN]',
'oauth_version' => '1.0');
$oauth['oauth_signature'] = base64_encode(hash_hmac('sha1', 'GET&' . rawurlencode($url) . '&' . rawurlencode(implode('&', array_map(function ($v, $k) { return $k . '=' . $v; }, $oauth, array_keys($oauth)))), '[CONSUMER SECRET]&[ACCESS TOKEN SECRET]', true));
$twitterData = json_decode(file_get_contents($url . '?count=' . $count, false, stream_context_create(array('http' => array('method' => 'GET',
'header' => 'Authorization: OAuth '
. implode(', ', array_map(function ($v, $k) { return $k . '="' . rawurlencode($v) . '"'; }, $oauth, array_keys($oauth))))))));
它使用匿名函数和file_get_contents而不是cURL库。注意使用MD5散列nonce。每个人似乎都暂时接受了time(),然而,web上关于OAuth的大多数示例都使用某种加密字符串(例如:http://www.sitepoint.com/understanding-oauth-1/)。这对我来说也更有意义。
进一步注意:匿名函数需要PHP 5.3+(以防您的服务器/计算机处于冷战洞穴中,无法升级)。
如在其他答案中所述,创建一个Twitter应用程序来获得令牌,密钥和秘密。
使用下面的代码,您可以从一个点修改请求参数,并避免拼写错误和类似的错误(在returnTweet()函数中更改$request数组)。
function buildBaseString($baseURI, $method, $params) {
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
}
function buildAuthorizationHeader($oauth) {
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
function returnTweet(){
$oauth_access_token = "x";
$oauth_access_token_secret = "x";
$consumer_key = "x";
$consumer_secret = "x";
$twitter_timeline = "user_timeline"; // mentions_timeline / user_timeline / home_timeline / retweets_of_me
// create request
$request = array(
'screen_name' => 'budidino',
'count' => '3'
);
$oauth = array(
'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'oauth_version' => '1.0'
);
// merge request and oauth to one array
$oauth = array_merge($oauth, $request);
// do some magic
$base_info = buildBaseString("https://api.twitter.com/1.1/statuses/$twitter_timeline.json", 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
// make request
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => "https://api.twitter.com/1.1/statuses/$twitter_timeline.json?". http_build_query($request),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
return json_decode($json, true);
}
然后调用returnTweet()