Home >Backend Development >PHP Tutorial >How to Retrieve a User's Twitter Timeline Using PHP and the v1.1 API?

How to Retrieve a User's Twitter Timeline Using PHP and the v1.1 API?

Linda Hamilton
Linda HamiltonOriginal
2024-12-17 06:40:25849browse

How to Retrieve a User's Twitter Timeline Using PHP and the v1.1 API?

Simplest PHP Example for Retrieving User Timeline with Twitter API Version 1.1

Introduction:

The Twitter API 1.0 has been retired, rendering the provided script ineffective. This article presents an updated solution and a PHP class to retrieve user timelines with minimal code.

Prerequisites:

  1. Create a Twitter developer account.
  2. Create an application and obtain consumer and access tokens.
  3. Modify the access level to Read & Write.

Solution:

Below is the simplified PHP code integrated with OAuth and the Twitter v1.1 API:

require_once('TwitterAPIExchange.php');

// Set access tokens
$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'
);

// Set request URL
$url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?count=10';
$requestMethod = 'GET';

// Instantiate Twitter API Exchange
$twitter = new TwitterAPIExchange($settings);

// Perform the request
$output = $twitter->buildOauth($url, $requestMethod)->performRequest();

// Decode and print tweets
$tweets = json_decode($output, true);
foreach ($tweets as $tweet) {
    print_r($tweet);
}

Implementation:

  1. Replace the access tokens with those obtained from your Twitter application.
  2. Adjust the 'count' parameter in the request URL to specify the desired number of tweets.
  3. Run the PHP script to retrieve and print the user's tweets.

The above is the detailed content of How to Retrieve a User's Twitter Timeline Using PHP and the v1.1 API?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn