Created
April 22, 2025 14:02
-
-
Save kasparsd/bc8a4d495d582c3a93f785643ee5fc0d to your computer and use it in GitHub Desktop.
X API get latest Tweets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Twitter { | |
private string $bearer; | |
public function __construct( string $bearer ) { | |
$this->bearer = $bearer; | |
} | |
public function get_rate_limits() { | |
$response = $this->get_from_api_url( 'https://api.x.com/1.1/application/rate_limit_status.json' ); | |
return $response->resources; | |
} | |
public function get( string $path, ?array $params = [] ) { | |
$api_url = sprintf( 'https://api.x.com/2/%s', trim( $path, '/\\' ) ); | |
if ( ! empty( $params ) ) { | |
$api_url .= '?' . http_build_query( $params ); | |
} | |
$response = $this->get_from_api_url( $api_url ); | |
return $response->data; | |
} | |
private function get_from_api_url( string $api_url ) { | |
$context = stream_context_create( | |
[ | |
'http' => [ | |
'method' => 'GET', | |
'header' => implode( | |
"\r\n", | |
[ | |
'Authorization: Bearer ' . $this->bearer, | |
'Content-Type: application/json', | |
] | |
), | |
], | |
] | |
); | |
return json_decode( file_get_contents( $api_url, false, $context ) ); | |
} | |
} | |
$bearer = getenv( 'TWITTER_BEARER' ); | |
$twitter = new Twitter( $bearer ); | |
// Get the author ID. | |
// $users = $twitter->get( 'users/by', [ 'usernames' => 'YOUR_USERNAME', 'tweet.fields' => 'author_id' ] ); | |
$user_id = 123456789; // Replace with the actual user ID. | |
$limits = $twitter->get_rate_limits(); | |
file_put_contents( 'limits.json', json_encode( $limits, JSON_PRETTY_PRINT ) ); | |
$tweets = $twitter->get( | |
sprintf( 'users/%d/tweets', $user_id ), | |
[ | |
'tweet.fields' => 'created_at,attachments,in_reply_to_user_id,public_metrics,referenced_tweets,text', | |
'media.fields' => 'preview_image_url,url', | |
'max_results' => 100, | |
] | |
); | |
if ( is_array( $tweets ) ) { | |
file_put_contents( 'tweets.json', json_encode( $tweets, JSON_PRETTY_PRINT ) ); | |
} else { | |
die( 'Error: ' . json_encode( $tweets ) ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment