2k views

Make calls to the twitter API in PHP (extremely easy)

The Twitter API is extremely simple. This function shows you how to communicate with the twitter API:

PHP
  1. /**
  2.   * Executes an API call
  3.   * @param string $twitter_method The Twitter method to call
  4.   * @param string $http_method The HTTP method to use
  5.   * @param string $format Return format
  6.   * @param array $options Options to pass to the Twitter method
  7.   * @param boolean $require_credentials Whether or not credentials are required
  8.   * @return string
  9.   */
  10. function apiCall($twitter_method, $http_method, $format, $options, $require_credentials = true)
  11. {
  12.      $credentials = "username:password"; // Replace for your own credentials
  13.  
  14.      $curl_handle = curl_init();
  15.      $api_url = sprintf('http://twitter.com/%s.%s', $twitter_method, $format);
  16.  
  17.      if (($http_method == 'get') && (count($options) > 0))
  18.      {
  19.          $api_url .= '?' . http_build_query($options);
  20.      }
  21.  
  22.      curl_setopt($curl_handle, CURLOPT_URL, $api_url);
  23.  
  24.      if ($require_credentials)
  25.      {
  26.          curl_setopt($curl_handle, CURLOPT_USERPWD, $credentials);
  27.      }
  28.      if ($http_method == 'post')
  29.      {
  30.          curl_setopt($curl_handle, CURLOPT_POST, true);
  31.          curl_setopt($curl_handle, CURLOPT_POSTFIELDS, http_build_query($options));
  32.      }
  33.  
  34.      curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
  35.      curl_setopt($curl_handle, CURLOPT_HTTPHEADER, array('Expect:'));
  36.  
  37.      $twitter_data = curl_exec($curl_handle);
  38.  
  39.      curl_close($curl_handle);
  40.  
  41.      return $twitter_data;
  42. }
  43.  

­

Some examples:

PHP
  1. // Gets the 20 most recent statuses
  2. apiCall('statuses/user_timeline', 'get', 'xml', array(), true);
  3.  
  4. // Update the twitter status
  5. apiCall('statuses/update', 'post',  'json', array('status' => 'This is what I am doing!'));
  6.  

­

To learn more about all the methods provided by the api of twitter: Twitter API Documentation

Tags: PHP twitter api curl REST

Embed: