Jump to content

Using Twitter Search API with PHP


Guest showstopper09
 Share

Recommended Posts

Guest showstopper09

Hi together,

i would like to write a php tool, which display searchresults on website.

Kind of http://twistori.com/

How should i do it? I know how to use PHP and html a bit, but i do not get totally the concept of how to work with the twitter api. Pleaz give me some help, so that i can understand the first steps.

Thanks,

Martin

Link to comment
Share on other sites

Hi together,

i would like to write a php tool, which display searchresults on website.

Kind of http://twistori.com/

How should i do it? I know how to use PHP and html a bit, but i do not get totally the concept of how to work with the twitter api. Pleaz give me some help, so that i can understand the first steps.

Thanks,

Martin

Your going to need to look into the cURL for PHP (http://php.net/manual/en/book.curl.php)

You will need to read about how to interface with the Twitter API (http://apiwiki.twitter.com/Libraries#PHP)

And then your going to need to look into JavaScript, if you want it to look like twistori.com.

The basics are, download Status, then filter / display.

Best way to do this is with Ajax, so that your page loading wont lag. best thing about Twitter is all the functions you need are already writen for you.

http://www.phpclasses.org/browse/file/20197.html - Contains all the functions you will need to access twitter.

Link to comment
Share on other sites

okays, so i got bored, and wrote a very basic version of this.

index.php

<?php 
$key = 'i wish';
include('search.php');
$twitter_query= '"'.$key.'"';
$search = new TwitterSearch($twitter_query);
$results = $search->results();


foreach($results as $result){
        $status=toLink($result->text);
        $pos = stripos($status,$key);
        echo "<div>";
        echo substr($status,0,$pos)."<br />";
        echo "<b>".strtoupper($key)."</b>".substr($status, $pos+count($key))."<br />";
        echo "</div>";
        //$display = $status.explode("i wish");
        //echo $display[0];

}
?>

search.php (Cred to Ryan Faerman <ryan.faerman@gmail.com>)

&lt;?
/**
 * Wrapper class around the Twitter Search API for PHP
 * Based on the class originally developed by David Billingham
 * and accessible at http://twitter.slawcup.com/twitter.class.phps
 * @author Ryan Faerman &lt;ryan.faerman@gmail.com&gt;
 * @version 0.2
 * @package PHPTwitterSearch
 */
class TwitterSearch {
    /**
     * Can be set to JSON (requires PHP 5.2 or the json pecl module) or XML - json|xml
     * @var string
     */
    var $type = 'json';
    
    /**
     * It is unclear if Twitter header preferences are standardized, but I would suggest using them.
     * More discussion at http://tinyurl.com/3xtx66
     * @var array
     */
    var $headers=array('X-Twitter-Client: PHPTwitterSearch','X-Twitter-Client-Version: 0.1','X-Twitter-Client-URL: http://ryanfaerman.com/twittersearch');
    
    /**
     * Recommend setting a user-agent so Twitter knows how to contact you inc case of abuse. Include your email
     * @var string
     */
    var $user_agent='';
    
    /**
     * @var string
     */
    var $query='';
    
    /**
     * @var array
     */
    var $responseInfo=array();
    
    /**
     * Use an ISO language code. en, de...
     * @var string
     */
    var $lang;
    
    /**
     * The number of tweets to return per page, max 100
     * @var int
     */
    var $rpp;
    
    /**
     * The page number to return, up to a max of roughly 1500 results
     * @var int
     */
    var $page;
    
    /**
     * Return tweets with a status id greater than the since value
     * @var int
     */
    var $since;
    
    /**
     * Returns tweets by users located within a given radius of the given latitude/longitude, where the user's location is taken from their Twitter profile. The parameter value is specified by "latitide,longitude,radius", where radius units must be specified as either "mi" (miles) or "km" (kilometers)
     * @var string
     */
    var $geocode;
    
    /**
     * When "true", adds "&lt;user&gt;:" to the beginning of the tweet. This is useful for readers that do not display Atom's author field. The default is "false"
     * @var boolean
     */
    var $show_user = false;
    
    /**
    * @param string $query optional
    */
    function TwitterSearch($query=false) {
        $this-&gt;query = $query;
    }
    
    /**
    * Find tweets from a user
    * @param string $user required
    * @return object
    */
    function from($user) {
        $this-&gt;query .= ' from:'.str_replace('@', '', $user);
        return $this;
    }
    
    /**
    * Find tweets to a user
    * @param string $user required
    * @return object
    */
    function to($user) {
        $this-&gt;query .= ' to:'.str_replace('@', '', $user);
        return $this;
    }
    
    /**
    * Find tweets referencing a user
    * @param string $user required
    * @return object
    */
    function about($user) {
        $this-&gt;query .= ' @'.str_replace('@', '', $user);
        return $this;
    }
    
    /**
    * Find tweets containing a hashtag
    * @param string $user required
    * @return object
    */
    function with($hashtag) {
        $this-&gt;query .= ' #'.str_replace('#', '', $hashtag);
        return $this;
    }
    
    /**
    * Find tweets containing a word
    * @param string $user required
    * @return object
    */
    function contains($word) {
        $this-&gt;query .= ' '.$word;
        return $this;
    }
    
    /**
    * Set show_user to true
    * @return object
    */
    function show_user() {
        $this-&gt;show_user = true;
        return $this;
    }
    
    /**
    * @param int $since_id required
    * @return object
    */
    function since($since_id) {
        $this-&gt;since = $since_id;
        return $this;
    }
    
    /**
    * @param int $language required
    * @return object
    */
    function lang($language) {
        $this-&gt;lang = $language;
        return $this;
    }
    
    /**
    * @param int $n required
    * @return object
    */
    function rpp($n) {
        $this-&gt;rpp = $n;
        return $this;
    }
    
    /**
    * @param int $n required
    * @return object
    */
    function page($n) {
        $this-&gt;page = $n;
        return $this;
    }
    
    /**
    * @param float $lat required. lattitude
    * @param float $long required. longitude
    * @param int $radius required. 
    * @param string optional. mi|km
    * @return object
    */
    function geocode($lat, $long, $radius, $units='mi') {
        $this-&gt;geocode = $lat.','.$long.','.$radius.$units;
        return $this;
    }
    
    /**
    * Build and perform the query, return the results.
    * @param $reset_query boolean optional.
    * @return object
    */
    function results($reset_query=true) {
        $request  = 'http://search.twitter.com/search.'.$this-&gt;type;
        $request .= '?q='.urlencode($this-&gt;query);
        
        if(isset($this-&gt;rpp)) {
            $request .= '&amp;rpp='.$this-&gt;rpp;
        }
        
        if(isset($this-&gt;page)) {
            $request .= '&amp;page='.$this-&gt;page;
        }
        
        if(isset($this-&gt;lang)) {
            $request .= '〈='.$this-&gt;lang;
        }
        
        if(isset($this-&gt;since)) {
            $request .= '&amp;since_id='.$this-&gt;since;
        }
        
        if($this-&gt;show_user) {
            $request .= '&amp;show_user=true';
        }
        
        if(isset($this-&gt;geocode)) {
            $request .= '&amp;geocode='.$this-&gt;geocode;
        }
        
        if($reset_query) {
            $this-&gt;query = '';
        }
        
        return $this-&gt;objectify($this-&gt;process($request))-&gt;results;
    }
    
    /**
    * Returns the top ten queries that are currently trending on Twitter.
    * @return object
    */
    function trends() {
        $request  = 'http://search.twitter.com/trends.json';
        
        return $this-&gt;objectify($this-&gt;process($request));
    }
    
    /**
     * Internal function where all the juicy curl fun takes place
     * this should not be called by anything external unless you are
     * doing something else completely then knock youself out.
     * @access private
     * @param string $url Required. API URL to request
     * @param string $postargs Optional. Urlencoded query string to append to the $url
     */
    function process($url, $postargs=false) {
        $ch = curl_init($url);
        if($postargs !== false) {
            curl_setopt ($ch, CURLOPT_POST, true);
            curl_setopt ($ch, CURLOPT_POSTFIELDS, $postargs);
        }
        
        curl_setopt($ch, CURLOPT_VERBOSE, 1);
        curl_setopt($ch, CURLOPT_NOBODY, 0);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_USERAGENT, $this-&gt;user_agent);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this-&gt;headers);

        $response = curl_exec($ch);
        
        $this-&gt;responseInfo=curl_getinfo($ch);
        curl_close($ch);
        
        if( intval( $this-&gt;responseInfo['http_code'] ) == 200 )
            return $response;    
        else
            return false;
    }
    
    /**
     * Function to prepare data for return to client
     * @access private
     * @param string $data
     */
    function objectify($data) {
        if( $this-&gt;type ==  'json' )
            return (object) json_decode($data);

        else if( $this-&gt;type == 'xml' ) {
            if( function_exists('simplexml_load_string') ) {
                $obj = simplexml_load_string( $data );

                $statuses = array();
                foreach( $obj-&gt;status as $status ) {
                    $statuses[] = $status;
                }
                return (object) $statuses;
            }
            else {
                return $out;
            }
        }
        else
            return false;
    }
}

?&gt;

&lt;?php
function toLink($text){
        $text = html_entity_decode($text);
        $text = " ".$text;
        $text = eregi_replace('(((f|ht){1}tp://)[-a-zA-Z0-9@:%_\+.~#?&amp;//=]+)',
                '&lt;a href="\\1"&gt;\\1&lt;/a&gt;', $text);
        $text = eregi_replace('(((f|ht){1}tps://)[-a-zA-Z0-9@:%_\+.~#?&amp;//=]+)',
                '&lt;a href="\\1"&gt;\\1&lt;/a&gt;', $text);
        $text = eregi_replace('([[:space:]()[{}])(www.[-a-zA-Z0-9@:%_\+.~#?&amp;//=]+)',
        '\\1&lt;a href="http://\\2"&gt;\\2&lt;/a&gt;', $text);
        $text = eregi_replace('([_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,3})',
        '&lt;a href="mailto:\\1"&gt;\\1&lt;/a&gt;', $text);
        return $text;
}
?&gt;

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...