Showing posts with label use. Show all posts
Showing posts with label use. Show all posts

Monday, 16 May 2016

5. [How-to] Implement and use Twitter streaming API using PHP

I downloaded the PHP source code and used: https://github.com/fennb/phirehose
Then I uploaded all the folders and files into my PHP server on Arvixe, or you can use 000webhost or x10hosting.

I used the filter-oauth.php file they included as a sample and replace the TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_TOKEN, and OAUTH_SECRET with my own codes from my Twitter developer account.

To get real-time tweets related to specific keywords, change the array of keywords (ie. morning, goodnight, hello, the) to whatever you like in the filter-oauth.php file:
$sc->setTrack(array('morning', 'goodnight', 'hello', 'the'));

To get a random of sample real-time tweets, use the sample.php file and again replace the TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET, OAUTH_TOKEN, and OAUTH_SECRET.
To test the real-time streaming Twitter API tweets, open your filter-oauth.php file in a web browser like Google Chrome: http://gerrycao.com/pinkarmr/streaming/example/sample.php

This is my sample.php file:
 <?php  
 require_once('../lib/Phirehose.php');  
 require_once('../lib/OauthPhirehose.php');  
   
 /**  
  * Example of using Phirehose to display the 'sample' twitter stream.  
  */  
 class SampleConsumer extends OauthPhirehose  
 {  
  /**  
   * Enqueue each status  
   *  
   * @param string $status  
   */  
  public function enqueueStatus($status)  
  {  
   /*  
    * In this simple example, we will just display to STDOUT rather than enqueue.  
    * NOTE: You should NOT be processing tweets at this point in a real application, instead they should be being  
    *    enqueued and processed asyncronously from the collection process.  
    */  
   $data = json_decode($status, true);  
   if (is_array($data) && isset($data['user']['screen_name'])) {  
    print $data['user']['screen_name'] . ': ' . urldecode($data['text']) . "<br /><hr />";  
   }  
  }  
 }  
   
 // The OAuth credentials you received when registering your app at Twitter  
 define("TWITTER_CONSUMER_KEY", "REPLACE_WITH_YOUR_OWN");  
 define("TWITTER_CONSUMER_SECRET", "REPLACE_WITH_YOUR_OWN");  
   
   
 // The OAuth data for the twitter account  
 define("OAUTH_TOKEN", "REPLACE_WITH_YOUR_OWN");  
 define("OAUTH_SECRET", "REPLACE_WITH_YOUR_OWN");  
   
 // Start streaming  
 $sc = new SampleConsumer(OAUTH_TOKEN, OAUTH_SECRET, Phirehose::METHOD_FILTER);  
 $sc->setTrack(array('morning', 'goodnight', 'hello', 'the'));  
 $sc->consume();  
 ?>  
   
Feel free to leave me a comment below for any clarifications or questions or comments.
[Last updated: 5/16/2016]

Thank you for not blocking our ads =)

Please consider adding this blog to the whitelist of your ads blocker :)