将Twitter短网址转换为原始网页并获取包含该网址的推文数量

时间:2013-12-24 11:01:58

标签: php url twitter

这里我从推文获取网址,将该网址转换为长网址。

然后获取包含该网址的推文数量的计数值。

$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;
    }

问题

  1. 再次解码一些推特微小的网址给了biturl(即再次微小的网址)
  2. 获取该推文的数量(计数值)包含该网址。上面的代码给出了它,但对于大多数网址,它显示0虽然它们有计数值
  3. 有任何改进建议吗?

1 个答案:

答案 0 :(得分:2)

如果您希望从短网址获取最后一个网址,则可以使用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;
}

获取推文数量,您可以使用此功能:

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;
}

所以这里是使用这个函数的例子:

$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";

输出类似于:

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