Wednesday 17 April 2013

Get tweet count by hashtag

Twitter API

http://search.twitter.com/search.json?q=your_hashtag&page=1

PHP Code

PHP code snippet for getting the Tweet data into the JSON format from Twitter API by using the CURL method.

<?php
if (isset($_POST['search_hash'])) {
    global $total, $hashtag;
    $hashtag = '#' . $_POST['search_hash'];
    $total = 0;

    function getTweets($hashtag, $page) {
        global $total;
        $url = 'http://search.twitter.com/search.json?q=' . urlencode($hashtag) . '&';
        $url .= 'page=' . $page;
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        $json = curl_exec($ch);
        curl_close($ch);

        $json_data = json_decode($json);
        $total += count($json_data->results);
        if ($json_data->next_page) {
            $temp = explode("&", $json_data->next_page);
            $p = explode("=", $temp[0]);
            getTweets($hashtag, $p[1]);
        }
        return $json_data;
    }

    $tweet = getTweets($hashtag, 1);
}
?>

HTML Form

<form  method="POST" action="tweets.php">
    <input type="text" name="search_hash">
    <input type="submit" value="Search" name="submit"/>
</form>

Tweet count and tabular listing of user name and tweets

<h4>Total Tweet Count : <?php echo $total; ?></h4>
<table>
       <th>User Name</th>
       <th>Text</th>

       <?php foreach ($tweet->results as $data) : ?>
       <tr>
       <td><?php echo $data->from_user_name; ?></td>
       <td><?php echo $data->text; ?></td>
       </tr>
       <?php endforeach; ?>
</table>

No comments:

Post a Comment