PHP - Twitter API (OAuth) 分页无法正常工作
PHP - Twitter API (OAuth) with pagination not working properly
我已经集成了 Twitter API (Twitter OAuth) 以获取特定公司帐户的最新提要,下面是我到目前为止所做的代码 (https://tomelliott.com/php/authenticating-twitter-feed-timeline-oauth)。
<?php
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser = "CompanyName";
$notweets = 3;
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets);
?>
<?php foreach ($tweets as $current_tweet) { ?>
<div class="card">
<div class="card-body">
<div class="media">
<div class="media-body">
<h5 class="F-20 themeFontGrey MontSemBold text-uppercase">REGENCY CORPORATE</h5>
<p class="MontRegular themeFontGrey">
<?php
$date = $current_tweet->created_at;
echo date("F d Y, H:i A", strtotime($date));
?>
</p>
</div>
<?php
$twitt_url = '#';
$twitter_target = '';
if (!empty($current_tweet->id)) {
$twitt_url = 'https://twitter.com/' . $twitteruser . '/status/' . $current_tweet->id;
$twitter_target = 'target="_blank"';
}
?>
<a href="<?php echo $twitt_url; ?>" class="hovicon effect-5 news-icon" <?php echo $twitter_target; ?> >
<i class="fa fa-twitter"></i>
</a>
</div>
<p class="MontRegular themeFontGrey">
<?php echo $current_tweet->text; ?>
</p>
</div>
<?php if (!empty($current_tweet->entities->media[0]->media_url)) { ?>
<div class="newsImages">
<img src="<?php echo $current_tweet->entities->media[0]->media_url; ?>" alt="Images" height="20%" width="20%" />
</div>
<?php
} ?>
<hr />
</div>
<?php
} ?>
效果很好,我收到了 3 条最新的推文。现在我想在其中添加分页,因此我遵循了 Twitter (https://developer.twitter.com/en/docs/basics/cursoring.html) 提供的文档,下面是我使用 cursor
更新的代码,并打印了数组(响应)。
<?php
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser = "CompanyName";
$notweets = 3;
$cursor = -1;
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets . "&cursor=" . $cursor);
echo '<pre>';
print_r($tweets);
exit;
?>
如您所见,我在这里添加了 $cursor = -1;
并将我的 api 目标 url 更新为 $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets . "&cursor=" . $cursor);
,传递了 cursor
值。
这里我收到了 3 条最近的推文,但是,根据上面 link (https://developer.twitter.com/en/docs/basics/cursoring.html) 文档中提到的,您应该会得到如下回复。
{
"ids": [
385752029,
602890434,
...
333181469,
333165023
],
"next_cursor": 1374004777531007833,
"next_cursor_str": "1374004777531007833",
"previous_cursor": 0,
"previous_cursor_str": "0"
}
我也尝试将请求的供稿 url 更新为此。
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&cursor=" . $cursor);
但到目前为止,我没有以任何方式获得 next_cursor
之类的任何密钥,无法继续。有人可以指导我,我在这里做错了什么,我应该怎么做才能从这里开始分页?
如有任何帮助或建议,我们将不胜感激。
谢谢
Refer Link :: Github :: https://github.com/dineshghule321/codebird-php
使用 Codebird 连接到 Twitter REST API、Streaming API、Collections API、TON(Object Nest)API 和 Twitter Ads API 来自你的 PHP 代码——全部只使用一个库。 Codebird 支持完整的 3 向 OAuth 以及仅限应用程序的身份验证。
由于 Twitter 的实时性,标准分页方法不适用于 GET statuses/user_timeline
等方法。
https://developer.twitter.com/en/docs/tweets/timelines/guides/working-with-timelines
您所请求的游标仅适用于需要检索非常大的数据而不是一次性检索所有方法的情况,例如 GET friends/ids
,您可以在其中发送 cursor
作为一个参数。换句话说,该方法需要支持 cursor
作为参数。
好的伙计们,
我找到了自己的方法来解决此问题,以使用我已经使用过的相同库集成 ajax 分页。这是我所做的方式。
我创建了两个页面。一个发送ajax请求抓取结果中的数据(page1.php),第二个页面是抓取api并基于ajax请求 (twitter_posts_ajax.php).
page1.php
<div class="col-xs-12 twitter_posts">
</div>
<script>
$( document ).ready(function() {
$.ajax({
type: 'POST',
url: "twitter_posts_ajax.php",
dataType: "html",
success: function(resultData) {
console.log(resultData);
$( ".twitter_posts" ).html(resultData);
}
});
$(document).on('click', '.twitter_posts_anchor', function(){
var twitterpagenumber = $(this).data('twitterpagenumber');
var myKeyVals = { twitterInpage : twitterpagenumber}
$.ajax({
type: 'POST',
url: "twitter_posts_ajax.php",
data: myKeyVals,
dataType: "html",
success: function(resultData) {
console.log(resultData);
$( ".twitter_posts" ).html(resultData);
$('html, body').animate({
scrollTop: $( '.twitter_posts' ).offset().top
}, 500);
}
});
});
});
twitter_posts_ajax.php
<?php
session_start();
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser = "CompanyName";
$limit = 10; //per page
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
if (!isset($_SESSION['twitter_total_pages'])) {
// Counting all tweets first
$count_all_tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser);
$twitter_total_pages = ceil(count($count_all_tweets) / $limit);
$_SESSION['twitter_total_pages'] = $twitter_total_pages;
} else {
$twitter_total_pages = $_SESSION['twitter_total_pages'];
}
$twitterInpage = !empty($_POST['twitterInpage']) ? (int)$_POST['twitterInpage'] : 1;
$totalPages = $_SESSION['twitter_total_pages']; //calculate total pages
$twitterInpage = max($twitterInpage, 1); //get 1 page when $_GET['page'] <= 0
$twitterInpage = min($twitterInpage, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($twitterInpage - 1) * $limit;
if ($offset < 0) $offset = 0;
$link = '?twitterInpage=%d';
$pagerContainer = '<div style="width: 300px;" class="linkedin_pagination">';
if ($totalPages != 0) {
if ($twitterInpage == 1) {
$pagerContainer .= '';
} else {
$page_number = $twitterInpage - 1;
$pagerContainer .= sprintf('<a href="javascript:void(0)" style="color: #c00" class="twitter_posts_anchor" data-twitterpagenumber=' . $page_number . '> « prev page</a>');
}
$pagerContainer .= ' <span> page <strong>' . $twitterInpage . '</strong> from ' . $totalPages . '</span>';
if ($twitterInpage == $totalPages) {
$pagerContainer .= '';
} else {
$page_number = $twitterInpage + 1;
$pagerContainer .= sprintf('<a href="javascript:void(0)" style="color: #c00" class="twitter_posts_anchor" data-twitterpagenumber=' . $page_number . '> next page » </a>');
}
}
$pagerContainer .= '</div>';
if ($twitterInpage == $_SESSION['twitter_total_pages']) {
$twitter_page_number = $_SESSION['twitter_total_pages'];
} else {
$twitter_page_number = ($page_number - 1);
}
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&page=" . $twitter_page_number . "&count=" . $limit);
?>
<?php foreach ($tweets as $current_tweet) { ?>
<div class="card">
<div class="card-body">
<div class="media">
<div class="newsIcon">
<img src="img/theme-logo-icon.png" alt="logo" />
</div>
<div class="media-body">
<h5 class="F-20 themeFontGrey MontSemBold text-uppercase">REGENCY CORPORATE</h5>
<p class="MontRegular themeFontGrey">
<?php
$date = $current_tweet->created_at;
echo date("F d Y, H:i A", strtotime($date));
?>
</p>
</div>
<?php
$twitt_url = '#';
$twitter_target = '';
if (!empty($current_tweet->id)) {
$twitt_url = 'https://twitter.com/' . $twitteruser . '/status/' . $current_tweet->id;
$twitter_target = 'target="_blank"';
}
?>
<a href="<?php echo $twitt_url; ?>" class="hovicon effect-5 news-icon" <?php echo $twitter_target; ?> >
<i class="fa fa-twitter"></i>
</a>
</div>
<p class="MontRegular themeFontGrey">
<?php echo $current_tweet->text; ?>
</p>
</div>
<?php if (!empty($current_tweet->entities->media[0]->media_url)) { ?>
<div class="newsImages">
<img src="<?php echo $current_tweet->entities->media[0]->media_url; ?>" alt="Images" />
</div>
<?php
} ?>
</div>
<?php
} ?>
<?php echo $pagerContainer; ?>
在这里,如您所见,我们有两个页面,page1.php,我正在通过它们传递 ajax 从 [=32 加载数据的请求=]twitter_posts_ajax.php。
我还在twitter_posts_ajax.php中使用了session_start()
只抓取推文总数一次,这样我就不需要每次都重新计算了。我还使用 offset
和 limit
进行分页,这与 ajax
.
配合得很好
希望这对您有所帮助。
我已经集成了 Twitter API (Twitter OAuth) 以获取特定公司帐户的最新提要,下面是我到目前为止所做的代码 (https://tomelliott.com/php/authenticating-twitter-feed-timeline-oauth)。
<?php
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser = "CompanyName";
$notweets = 3;
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets);
?>
<?php foreach ($tweets as $current_tweet) { ?>
<div class="card">
<div class="card-body">
<div class="media">
<div class="media-body">
<h5 class="F-20 themeFontGrey MontSemBold text-uppercase">REGENCY CORPORATE</h5>
<p class="MontRegular themeFontGrey">
<?php
$date = $current_tweet->created_at;
echo date("F d Y, H:i A", strtotime($date));
?>
</p>
</div>
<?php
$twitt_url = '#';
$twitter_target = '';
if (!empty($current_tweet->id)) {
$twitt_url = 'https://twitter.com/' . $twitteruser . '/status/' . $current_tweet->id;
$twitter_target = 'target="_blank"';
}
?>
<a href="<?php echo $twitt_url; ?>" class="hovicon effect-5 news-icon" <?php echo $twitter_target; ?> >
<i class="fa fa-twitter"></i>
</a>
</div>
<p class="MontRegular themeFontGrey">
<?php echo $current_tweet->text; ?>
</p>
</div>
<?php if (!empty($current_tweet->entities->media[0]->media_url)) { ?>
<div class="newsImages">
<img src="<?php echo $current_tweet->entities->media[0]->media_url; ?>" alt="Images" height="20%" width="20%" />
</div>
<?php
} ?>
<hr />
</div>
<?php
} ?>
效果很好,我收到了 3 条最新的推文。现在我想在其中添加分页,因此我遵循了 Twitter (https://developer.twitter.com/en/docs/basics/cursoring.html) 提供的文档,下面是我使用 cursor
更新的代码,并打印了数组(响应)。
<?php
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser = "CompanyName";
$notweets = 3;
$cursor = -1;
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets . "&cursor=" . $cursor);
echo '<pre>';
print_r($tweets);
exit;
?>
如您所见,我在这里添加了 $cursor = -1;
并将我的 api 目标 url 更新为 $tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&count=" . $notweets . "&cursor=" . $cursor);
,传递了 cursor
值。
这里我收到了 3 条最近的推文,但是,根据上面 link (https://developer.twitter.com/en/docs/basics/cursoring.html) 文档中提到的,您应该会得到如下回复。
{
"ids": [
385752029,
602890434,
...
333181469,
333165023
],
"next_cursor": 1374004777531007833,
"next_cursor_str": "1374004777531007833",
"previous_cursor": 0,
"previous_cursor_str": "0"
}
我也尝试将请求的供稿 url 更新为此。
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&cursor=" . $cursor);
但到目前为止,我没有以任何方式获得 next_cursor
之类的任何密钥,无法继续。有人可以指导我,我在这里做错了什么,我应该怎么做才能从这里开始分页?
如有任何帮助或建议,我们将不胜感激。
谢谢
Refer Link :: Github :: https://github.com/dineshghule321/codebird-php
使用 Codebird 连接到 Twitter REST API、Streaming API、Collections API、TON(Object Nest)API 和 Twitter Ads API 来自你的 PHP 代码——全部只使用一个库。 Codebird 支持完整的 3 向 OAuth 以及仅限应用程序的身份验证。
由于 Twitter 的实时性,标准分页方法不适用于 GET statuses/user_timeline
等方法。
https://developer.twitter.com/en/docs/tweets/timelines/guides/working-with-timelines
您所请求的游标仅适用于需要检索非常大的数据而不是一次性检索所有方法的情况,例如 GET friends/ids
,您可以在其中发送 cursor
作为一个参数。换句话说,该方法需要支持 cursor
作为参数。
好的伙计们,
我找到了自己的方法来解决此问题,以使用我已经使用过的相同库集成 ajax 分页。这是我所做的方式。
我创建了两个页面。一个发送ajax请求抓取结果中的数据(page1.php),第二个页面是抓取api并基于ajax请求 (twitter_posts_ajax.php).
page1.php
<div class="col-xs-12 twitter_posts">
</div>
<script>
$( document ).ready(function() {
$.ajax({
type: 'POST',
url: "twitter_posts_ajax.php",
dataType: "html",
success: function(resultData) {
console.log(resultData);
$( ".twitter_posts" ).html(resultData);
}
});
$(document).on('click', '.twitter_posts_anchor', function(){
var twitterpagenumber = $(this).data('twitterpagenumber');
var myKeyVals = { twitterInpage : twitterpagenumber}
$.ajax({
type: 'POST',
url: "twitter_posts_ajax.php",
data: myKeyVals,
dataType: "html",
success: function(resultData) {
console.log(resultData);
$( ".twitter_posts" ).html(resultData);
$('html, body').animate({
scrollTop: $( '.twitter_posts' ).offset().top
}, 500);
}
});
});
});
twitter_posts_ajax.php
<?php
session_start();
require_once("twitteroauth/twitteroauth.php"); //Path to twitteroauth library
$twitteruser = "CompanyName";
$limit = 10; //per page
$consumerkey = "xxxxxxxx";
$consumersecret = "xxxxxxxx";
$accesstoken = "xxxxxxxx";
$accesstokensecret = "xxxxxxxx";
function getConnectionWithAccessToken($cons_key, $cons_secret, $oauth_token, $oauth_token_secret)
{
$connection = new TwitterOAuth($cons_key, $cons_secret, $oauth_token, $oauth_token_secret);
return $connection;
}
$connection = getConnectionWithAccessToken($consumerkey, $consumersecret, $accesstoken, $accesstokensecret);
if (!isset($_SESSION['twitter_total_pages'])) {
// Counting all tweets first
$count_all_tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser);
$twitter_total_pages = ceil(count($count_all_tweets) / $limit);
$_SESSION['twitter_total_pages'] = $twitter_total_pages;
} else {
$twitter_total_pages = $_SESSION['twitter_total_pages'];
}
$twitterInpage = !empty($_POST['twitterInpage']) ? (int)$_POST['twitterInpage'] : 1;
$totalPages = $_SESSION['twitter_total_pages']; //calculate total pages
$twitterInpage = max($twitterInpage, 1); //get 1 page when $_GET['page'] <= 0
$twitterInpage = min($twitterInpage, $totalPages); //get last page when $_GET['page'] > $totalPages
$offset = ($twitterInpage - 1) * $limit;
if ($offset < 0) $offset = 0;
$link = '?twitterInpage=%d';
$pagerContainer = '<div style="width: 300px;" class="linkedin_pagination">';
if ($totalPages != 0) {
if ($twitterInpage == 1) {
$pagerContainer .= '';
} else {
$page_number = $twitterInpage - 1;
$pagerContainer .= sprintf('<a href="javascript:void(0)" style="color: #c00" class="twitter_posts_anchor" data-twitterpagenumber=' . $page_number . '> « prev page</a>');
}
$pagerContainer .= ' <span> page <strong>' . $twitterInpage . '</strong> from ' . $totalPages . '</span>';
if ($twitterInpage == $totalPages) {
$pagerContainer .= '';
} else {
$page_number = $twitterInpage + 1;
$pagerContainer .= sprintf('<a href="javascript:void(0)" style="color: #c00" class="twitter_posts_anchor" data-twitterpagenumber=' . $page_number . '> next page » </a>');
}
}
$pagerContainer .= '</div>';
if ($twitterInpage == $_SESSION['twitter_total_pages']) {
$twitter_page_number = $_SESSION['twitter_total_pages'];
} else {
$twitter_page_number = ($page_number - 1);
}
$tweets = $connection->get("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" . $twitteruser . "&page=" . $twitter_page_number . "&count=" . $limit);
?>
<?php foreach ($tweets as $current_tweet) { ?>
<div class="card">
<div class="card-body">
<div class="media">
<div class="newsIcon">
<img src="img/theme-logo-icon.png" alt="logo" />
</div>
<div class="media-body">
<h5 class="F-20 themeFontGrey MontSemBold text-uppercase">REGENCY CORPORATE</h5>
<p class="MontRegular themeFontGrey">
<?php
$date = $current_tweet->created_at;
echo date("F d Y, H:i A", strtotime($date));
?>
</p>
</div>
<?php
$twitt_url = '#';
$twitter_target = '';
if (!empty($current_tweet->id)) {
$twitt_url = 'https://twitter.com/' . $twitteruser . '/status/' . $current_tweet->id;
$twitter_target = 'target="_blank"';
}
?>
<a href="<?php echo $twitt_url; ?>" class="hovicon effect-5 news-icon" <?php echo $twitter_target; ?> >
<i class="fa fa-twitter"></i>
</a>
</div>
<p class="MontRegular themeFontGrey">
<?php echo $current_tweet->text; ?>
</p>
</div>
<?php if (!empty($current_tweet->entities->media[0]->media_url)) { ?>
<div class="newsImages">
<img src="<?php echo $current_tweet->entities->media[0]->media_url; ?>" alt="Images" />
</div>
<?php
} ?>
</div>
<?php
} ?>
<?php echo $pagerContainer; ?>
在这里,如您所见,我们有两个页面,page1.php,我正在通过它们传递 ajax 从 [=32 加载数据的请求=]twitter_posts_ajax.php。
我还在twitter_posts_ajax.php中使用了session_start()
只抓取推文总数一次,这样我就不需要每次都重新计算了。我还使用 offset
和 limit
进行分页,这与 ajax
.
希望这对您有所帮助。