Getting latest tweet ID

php

#1

So I’m a bit new to using the Twitter API… scratch that, I’m a bit new to APIs in general, lol. But, I’m trying to get the latest tweet ID of a user (myself), and save it in a variable. Essentially, every time I press this button, I want it to fetch the latest tweet I’ve made, find the tweet id of that tweet, and save it in a variable. I’m using PHP, and I’m using @abraham TwitterOAuth. If anyone could help me, that would be greatly appreciated.


#2

Evening disband, this should work for you.

<?php
// The usual key/token/secret stuff that is required
$consumerKey = '';
$consumerSecret = '';
$OAuthToken = '';
$OAuthSecret = '';

require_once('./twitteroauth.php');

$tweet = new TwitterOAuth($consumerKey, $consumerSecret, $OAuthToken, $OAuthSecret);

// Here we are GETting just ONE status from my account
$foo = $tweet->get('statuses/user_timeline', array('screen_name' => '@dalehay', 'count' => 1));

// And now $tweetid is the variable that'll show your latest tweet ID
$tweetid = $foo[0]->id;

// Here's an example of how it can be used
echo "My most recent tweet's ID number is " . $tweetid;
?>

I used that (hence the random hello tweet to you) and it comes back with:

My most recent tweet's ID number is 677555879307251712

Hope that helps. :slight_smile:


#3

Note that require_once('./twitteroauth.php'); won’t work on modern version of TwitteroAuth. Instead you should install with composer and use:

require "vendor/autoload.php";
use Abraham\TwitterOAuth\TwitterOAuth;

#4

That is true @abraham, I should’ve pointed that out during my response to help anyone else reading this, but was just using the (older) files I use on my laptop. :slight_smile: