«Typecho 获取 Bilibili 关注和粉丝数量»
by pluvet on Jan 29, 2019

用到的 api: https://api.bilibili.com/x/relation/stat?vmid={mid}

代码:

function getFollowerCount($mid){
    $bilibili_url = "https://api.bilibili.com/x/relation/stat?vmid=".$mid;
    $obj = json_decode( downloadString($bilibili_url),true);
    return $obj['data']['follower'];
}

function downloadString($url){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_HEADER,0);
    $output = curl_exec($ch);
    curl_close($ch);
    return $output;
}

实际使用的时候, 应该设置超时时间等

    public static function getFollowerCount($mid)
    {
        $bilibili_url = "http://api.bilibili.com/x/relation/stat?vmid=" . $mid;
        $obj = json_decode(self::downloadString($bilibili_url), true);
        if(null!=$obj){
            return $obj['data']['follower'];
        }
        return -1;
        
    }

    private static function downloadString($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT ,1);
        $output = curl_exec($ch);
        /*if ($err = curl_error($ch)){
            echo $err;
            curl_close($ch);
            exit;
        }*/
        return $output;
    }

添加新评论