使用 Twitter API 1.1 版检索 user_timeline 的最简单 PHP 示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12916539/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest PHP example for retrieving user_timeline with Twitter API version 1.1
提问by fellowworldcitizen
Because of the Twitter API 1.0 retirement as of June 11th 2013, the script below does not work anymore.
由于 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);
}
}
How can I get the user_timeline (recent statuses) with the least code possible?
如何使用尽可能少的代码获取 user_timeline(最近状态)?
I found this: https://dev.twitter.com/docs/api/1.1/get/statuses/user_timelinebut I get the following error:
我发现了这个:https: //dev.twitter.com/docs/api/1.1/get/statuses/user_timeline但我收到以下错误:
"{"errors":[{"message":"Could not authenticate you","code":32}]}"
There are a lot of classes out there but after trying several none of them seem to work because of these updates at Twitter, plus some of them are pretty advanced classes with a lot of functionality that I don't really need.
那里有很多类,但是在尝试了几个类之后,由于 Twitter 上的这些更新,它们似乎都不起作用,而且其中一些是非常高级的类,具有很多我并不真正需要的功能。
What is the simplest/shortest way to get the recent user statuses with PHP?
使用 PHP 获取最近用户状态的最简单/最短方法是什么?
回答by Jimbo
Important Note:As of mid-2018, the process to get twitter API tokens became a lot more bureaucratic. It has taken me over one working weekto be provided a set of API tokens, and this is for an open source project for you guys and girls with over 1.2 million installationson Packagist and 1.6k stars on Github, which theoretically should be higher priority.
If you are tasked with working with the twitter API for your work, you must take this potentially extremely long wait-time into account. Also consider other social media avenues like Facebook or Instagram and provide these options, as the process for retrieving their tokens is instant.
重要提示:截至 2018 年年中,获取 Twitter API 令牌的过程变得更加官僚化。我花了一个多星期才得到一套 API 令牌,这是一个开源项目,在 Packagist 上安装量超过120 万,在 Github 上安装量超过1.6k,理论上应该优先级更高.
如果您的任务是使用 twitter API 来完成您的工作,您必须考虑到这个潜在的非常长的等待时间。还可以考虑其他社交媒体渠道,如 Facebook 或 Instagram,并提供这些选项,因为检索其代币的过程是即时的。
So you want to use the Twitter v1.1 API?
那么您想使用 Twitter v1.1 API 吗?
Note: the files for these are on GitHub.
Version 1.0 will soon be deprecatedand unauthorised requests won't be allowed. So, here's a post to help you do just that, along with a PHP class to make your life easier.
1.0 版很快将被弃用,并且不允许未经授权的请求。所以,这里有一篇文章可以帮助您做到这一点,还有一个 PHP 类可以让您的生活更轻松。
1. Create a developer account:Set yourself up a developer accounton Twitter
1. 创建一个开发者账号:在 Twitter 上为自己设置一个开发者账号
You need to visit the official Twitter developer site and register for a developer account. This is a freeand necessary step to make requests for the v1.1 API.
您需要访问官方 Twitter 开发者网站并注册一个开发者帐户。这是向 v1.1 API 发出请求的免费且必要的步骤。
2. Create an application:Create an application on the Twitter developer site
2. 创建应用程序:在 Twitter 开发者站点上创建应用程序
What? You thought you could make unauthenticated requests? Not with Twitter's v1.1 API. You need to visit http://dev.twitter.com/appsand click the "Create Application" button.
什么?您认为您可以提出未经身份验证的请求吗?不适用于 Twitter 的 v1.1 API。您需要访问http://dev.twitter.com/apps并单击“创建应用程序”按钮。


On this page, fill in whatever details you want. For me, it didn't matter, because I just wanted to make a load of block requests to get rid of spam followers. The point is you are going to get yourself a set of unique keysto use for your application.
在此页面上,填写您想要的任何详细信息。对我来说,这并不重要,因为我只想发出大量阻止请求以摆脱垃圾邮件关注者。关键是您将获得一组用于您的应用程序的唯一键。
So, the point of creating an application is to give yourself (and Twitter) a set of keys. These are:
因此,创建应用程序的重点是为您自己(和 Twitter)提供一组密钥。这些是:
- The consumer key
- The consumer secret
- The access token
- The access token secret
- 消费者密钥
- 消费者的秘密
- 访问令牌
- 访问令牌秘密
There's a little bit of information hereon what these tokens for.
还有的一点点信息在这里关于这些令牌。
3. Create access tokens: You'll need these to make successful requests
3. 创建访问令牌:您需要这些令牌才能成功请求
OAuthrequests a few tokens. So you need to have them generated for you.
OAuth请求一些令牌。所以你需要为你生成它们。


Click "create my access token" at the bottom. Then once you scroll to the bottom again, you'll have some newly generated keys. You need to grab the four previously labelled keys from this page for your API calls, so make a note of them somewhere.
单击底部的“创建我的访问令牌”。然后,一旦您再次滚动到底部,您将拥有一些新生成的密钥。您需要从此页面获取四个先前标记的键以进行 API 调用,因此请在某处记下它们。
4. Change access level: You don't want read-only, do you?
4. 更改访问级别:您不想要只读,对吗?
If you want to make any decent use of this API, you'll need to change your settings to Read & Write if you're doing anything other than standard data retrieval using GETrequests.
如果您想适当地使用此 API,如果您正在使用GET请求进行标准数据检索以外的任何其他操作,则需要将设置更改为 Read & Write 。


Choose the "Settings" tab near the top of the page.
选择页面顶部附近的“设置”选项卡。


Give your application read / write access, and hit "Update" at the bottom.
授予您的应用程序读/写访问权限,然后点击底部的“更新”。
You can read more about the applications permission modelthat Twitter uses here.
您可以在此处阅读有关Twitter 使用的应用程序权限模型的更多信息。
5. Write code to access the API: I've done most of it for you
5. 编写访问 API 的代码:我已经为您完成了大部分工作
I combined the code above, with some modifications and changes, into a PHP class so it's really simple to make the requests you require.
我将上面的代码,经过一些修改和更改,组合到一个 PHP 类中,因此发出您需要的请求非常简单。
This uses OAuthand the Twitter v1.1 API, and the class I've created which you can find below.
这使用OAuth和Twitter v1.1 API,以及我创建的类,您可以在下面找到。
require_once('TwitterAPIExchange.php');
/** Set access tokens here - see: https://dev.twitter.com/apps/ **/
$settings = array(
'oauth_access_token' => "YOUR_OAUTH_ACCESS_TOKEN",
'oauth_access_token_secret' => "YOUR_OAUTH_ACCESS_TOKEN_SECRET",
'consumer_key' => "YOUR_CONSUMER_KEY",
'consumer_secret' => "YOUR_CONSUMER_SECRET"
);
Make sure you put the keys you got from your application above in their respective spaces.
确保将您从上面的应用程序中获得的密钥放在各自的空间中。
Next you need to choose a URL you want to make a request to. Twitter has their API documentationto help you choose which URL and also the request type (POST or GET).
接下来,您需要选择要向其发出请求的 URL。Twitter 有他们的API 文档来帮助您选择哪个 URL 以及请求类型(POST 或 GET)。
/** URL for REST request, see: https://dev.twitter.com/docs/api/1.1/ **/
$url = 'https://api.twitter.com/1.1/blocks/create.json';
$requestMethod = 'POST';
In the documentation, each URL states what you can pass to it. If we're using the "blocks" URL like the one above, I can pass the following POST parameters:
在文档中,每个 URL 都说明了您可以传递给它的内容。如果我们像上面一样使用“blocks” URL,我可以传递以下 POST 参数:
/** POST fields required by the URL above. See relevant docs as above **/
$postfields = array(
'screen_name' => 'usernameToBlock',
'skip_status' => '1'
);
Now that you've set up what you want to do with the API, it's time to make the actual request.
现在您已经设置了您想要使用 API 执行的操作,现在是发出实际请求的时候了。
/** Perform the request and echo the response **/
$twitter = new TwitterAPIExchange($settings);
echo $twitter->buildOauth($url, $requestMethod)
->setPostfields($postfields)
->performRequest();
And for a POSTrequest, that's it!
对于POST请求,就是这样!
For a GETrequest, it's a little different. Here's an example:
对于GET请求,它有点不同。下面是一个例子:
/** Note: Set the GET field BEFORE calling buildOauth(); **/
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=J7mbo';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
Final code example: For a simple GET request for a list of my followers.
最终代码示例:对于我的关注者列表的简单 GET 请求。
$url = 'https://api.twitter.com/1.1/followers/list.json';
$getfield = '?username=J7mbo&skip_status=1';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
echo $twitter->setGetfield($getfield)
->buildOauth($url, $requestMethod)
->performRequest();
I've put these files on GitHubwith credit to @lackovic10 and @rivers! I hope someone finds it useful; I know I did (I used it for bulk blocking in a loop).
我已将这些文件放在 GitHub 上,感谢 @lackovic10 和 @rivers!我希望有人觉得它有用;我知道我做到了(我将它用于循环中的批量阻塞)。
Also, for those on Windows who are having problems with SSL certificates, look at this post. This library uses cURL under the hood so you need to make sure you have your cURL certs set up probably. Google is also your friend.
另外,对于那些在使用 SSL 证书时遇到问题的 Windows 用户,请查看这篇文章。该库在幕后使用 cURL,因此您需要确保可能设置了 cURL 证书。谷歌也是你的朋友。
回答by Rivers
Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation I've recently written with PHPand cURL.
转到 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);
?>
This can be run from the command line:
这可以从命令行运行:
$ php <name of PHP script>.php
回答by lackovic10
The code pasted by Rivers is great. Thanks a lot! I'm new here and can't comment, I'd just want to answer to the question from javiervd (How would you set the screen_name and count with this approach?), as I've lost a lot of time to figure it out.
Rivers 粘贴的代码很棒。非常感谢!我是新来的,无法发表评论,我只想回答 javirvd 的问题(你会如何设置 screen_name 并用这种方法计数?),因为我已经失去了很多时间来弄清楚出去。
You need to add the parameters both to the URLand to the signature creating process. Creating a signatureis the article that helped me. Here is my code:
您需要将参数添加到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
);
回答by budidino
Like stated in other answers, create a Twitter app to get the token, key and secret.
Using the code bellow, you can modify request parameters from one spot and avoid typos and similar errors (change $requestarray in returnTweet()function).
就像其他答案中所述,创建一个 Twitter 应用程序来获取令牌、密钥和秘密。使用下面的代码,您可以从一个地方修改请求参数并避免拼写错误和类似错误(更改函数中的$request数组returnTweet())。
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);
}
and then just call returnTweet()
然后就打电话 returnTweet()
回答by Frewuill
Thank you Kris!
谢谢克里斯!
It worked for me without using parameters to the query, whenever I used more than one parameter it showed me the error: 32 Could not authenticate you.
它在不使用查询参数的情况下对我有用,每当我使用多个参数时,它都会向我显示错误:32 无法对您进行身份验证。
The problem for me, was in the ampersand encoding. So in your code where it's the following line
对我来说,问题在于与号编码。所以在你的代码中,它是以下行
$url .= "?".http_build_query($query);
I added the following line below:
我在下面添加了以下行:
$url=str_replace("&","&",$url);
And it worked using two or more parameters like screen_name and count.
它使用两个或多个参数,如 screen_name 和 count。
The whole code looks like this:
整个代码如下所示:
$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '2'
);
$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'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// 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 .= "?".http_build_query($query);
$url=str_replace("&","&",$url); //Patch by @Frewuill
$oauth['oauth_signature'] = $signature; // don't want to abandon all that work!
ksort($oauth); // probably not necessary, but twitter's demo does it
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// 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);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
Hope It helps somebody with the same problem I had.
希望它可以帮助我遇到同样问题的人。
回答by Kris Reeves
This question helped me a lot but didn't get me all the way in understanding what needs to happen. This blog postdid an amazing job of walking me through it.
这个问题对我帮助很大,但并没有让我完全理解需要发生的事情。这篇博文在引导我完成它方面做得非常出色。
Here are the important bits all in one place:
以下是所有重要的部分:
- As pointed out above, you MUST sign your 1.1 API requests. If you are doing something like getting public statuses, you'll want an application key rather than a user key. The full link to the page you want is: https://dev.twitter.com/apps
- You must hash ALL the parameters, both the oauth ones AND the get parameters (or POST parameters) together.
- You must SORT the parameters before reducing them to the url encoded form that gets hashed.
- You must encode some things multiple times - for example, you create a query string from the parameters' url-encoded values, and then you url encode THAT and concatenate with the method type and the url.
- 如上所述,您必须签署 1.1 API 请求。如果您正在执行诸如获取公共状态之类的操作,您将需要应用程序密钥而不是用户密钥。您想要的页面的完整链接是:https: //dev.twitter.com/apps
- 您必须将所有参数散列在一起,包括 oauth 参数和 get 参数(或 POST 参数)。
- 您必须先对参数进行排序,然后再将它们减少为散列的 url 编码形式。
- 您必须对某些内容进行多次编码 - 例如,您从参数的 url 编码值创建一个查询字符串,然后对 THAT 进行 url 编码并与方法类型和 url 连接。
I sympathize with all the headaches, so here's some code to wrap it all up:
我同情所有的头痛,所以这里有一些代码来包装它:
$token = 'YOUR TOKEN';
$token_secret = 'TOKEN SECRET';
$consumer_key = 'YOUR KEY';
$consumer_secret = 'KEY SECRET';
$host = 'api.twitter.com';
$method = 'GET';
$path = '/1.1/statuses/user_timeline.json'; // api call path
$query = array( // query parameters
'screen_name' => 'twitterapi',
'count' => '2'
);
$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'
);
$oauth = array_map("rawurlencode", $oauth); // must be encoded before sorting
$query = array_map("rawurlencode", $query);
$arr = array_merge($oauth, $query); // combine the values THEN sort
asort($arr); // secondary sort (value)
ksort($arr); // primary sort (key)
// http_build_query automatically encodes, but our parameters
// are already encoded, and must be by this point, so we undo
// the encoding step
$querystring = urldecode(http_build_query($arr, '', '&'));
$url = "https://$host$path";
// 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 .= "?".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
// also not necessary, but twitter's demo does this too
function add_quotes($str) { return '"'.$str.'"'; }
$oauth = array_map("add_quotes", $oauth);
// 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);
// do our business
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$twitter_data = json_decode($json);
回答by jeffaudio
If you have the OAuth PHP library installed, you don't have to worry about forming the request yourself.
如果您安装了 OAuth PHP 库,则不必担心自己形成请求。
$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);
$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());
print_r($twitter_data);
For more information, check out The docsor their example. You can use pecl install oauthto get the library.
回答by Chanuka Asanka
First of all I wanted to thank jimbo and (his post/ twitter-api-php simple library).
首先我要感谢 jimbo 和(他的帖子/twitter-api-php 简单库)。
If you are going to use the GET search/tweets APIwith "twitter-api-php" PHP library (TwitterAPIExchange.php):
如果您打算将GET 搜索/推文 API与“twitter-api-php”PHP 库 (TwitterAPIExchange.php) 一起使用:
First, you have to just comment "Perform a POST request and echo the response " code area.
首先,您只需注释“执行 POST 请求并回显响应”代码区域。
Just use "Perform a GET request and echo the response" code and echo the response and change these two lines:
只需使用“执行 GET 请求并回显响应”代码并回显响应并更改这两行:
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';
to
到
$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=J7mbo';
(Change screen_nameto q, that's it :)
(更改screen_name为q,就是这样:)
回答by Matthew Rapati
You'll need a to create an "app" on Twitter(and you need a Twitter account to do this).
您需要在 Twitter 上创建一个“应用程序”(并且您需要一个 Twitter 帐户来执行此操作)。
Then, you need to use OAuth to make an authorized request to Twitter.
然后,您需要使用 OAuth 向 Twitter 发出授权请求。
You can use the GET statuses/user_timelineresource to get a list of recent tweets.
您可以使用GET statuses/user_timeline资源来获取最近推文的列表。
回答by kasimir
Here's a brief one for getting a specified number of tweets from your timeline. It basically does the same thing as the other examples, only with less code.
这是从您的时间线中获取指定数量推文的简短内容。它基本上与其他示例执行相同的操作,只是代码更少。
Just fill in the keys and adjust $countto your liking:
只需填写键并$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))))))));
This one uses anonymous functions and file_get_contentsinstead of the cURL library. Note the use of an MD5 hashed nonce. Everyone seems to be going along with the time()nonce, however, most examples on the web concerning OAuth use some kind of encrypted string (like this one: http://www.sitepoint.com/understanding-oauth-1/). This makes more sense to me too.
这个使用匿名函数而file_get_contents不是 cURL 库。请注意使用 MD5 散列随机数。每个人似乎都同意time()随机数,但是,网络上有关 OAuth 的大多数示例都使用某种加密字符串(例如:http: //www.sitepoint.com/understanding-oauth-1/)。这对我来说也更有意义。
Further note:you need PHP 5.3+ for the anonymous functions (in case your server/computer is in some cold war cave and you can't upgrade it).
进一步注意:匿名函数需要 PHP 5.3+(以防您的服务器/计算机处于冷战洞穴中并且无法升级)。

