user123
user123

Reputation: 5407

converting twitter short url to original and getting numbers of tweets containing that url

Here I am getting url from tweets, converting that url to long url.

And then getting count value for numbers of tweets containing that url.

$reg_exUrl = "/(?<![\>https?:\/\/|href=\"'])(?<http>(https?:[\/][\/]|www\.)([a-z]|[A-Z]|[0-9]|[\/.]|[~])*)/";
// The Text you want to filter for urls
$text = "Make this Xmas super powerful with #Krrish3 on http://t.co/PHOdAqnzkT !\ ";
// Check if there is a url in the text

    if(preg_match($reg_exUrl, $text, $url)) {
        preg_match_all($reg_exUrl, $text, $urls);
        foreach ($urls[0] as $url) {
        echo "{$url}<br>";
        $full = MyURLDecode($url);
        echo "full is: $full<br>";
        $feedUrl = "http://urls.api.twitter.com/1/urls/count.json?url=$full";
        $json = file_get_contents($feedUrl);
        $code = json_decode($json,true);
        var_dump($code);
        echo "1";
        echo "Numbers of tweets containing this link : ", $code['count'];
        echo "2";
    }
    } else {
    echo $text;
    }

Problem

  1. Decoding some twitter tiny urls again give biturl(i.e. again tiny url)
  2. Getting number of tweets(count value) containig that url. Above code give it, but for most of url it show 0 though they have count value

Any suggestion for improvement?

Upvotes: 1

Views: 842

Answers (1)

Glavić
Glavić

Reputation: 43552

If you wish to fetch last url from short url, you can use curl:

function get_follow_url($url) {
    $ch = curl_init();
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_HEADER => false,
        CURLOPT_NOBODY => true,
        CURLOPT_FOLLOWLOCATION => true,
    ));
    curl_exec($ch);
    $follow_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
    curl_close($ch);
    return $follow_url;
}

To fetch the number of tweets, you can use this function:

function get_twitter_url_count($url) {
    $encoded_url = urlencode($url);
    $content = @file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
    return $content ? json_decode($content)->count : 0;
}

So here is use example of this functions:

$short_url = 'http://t.co/5rgJb3mbQ6';
echo "Short url: $short_url\n";

$follow_url = get_follow_url($short_url);
echo "Follow url: $follow_url\n";

$url_count = get_twitter_url_count($follow_url);
echo "Url count: $url_count\n";

Output would be something like:

Short url: http://t.co/5rgJb3mbQ6
Follow url: http://global.yamaha-motor.com/race/wgp-50th/race_archive/riders/hideo_kanaya/
Url count: 6

Upvotes: 2

Related Questions