php获取最新github仓库

5 年前(已编辑)
1010
这篇文章上次修改于 3 年前,可能部分内容已经不适用,如有疑问可询问作者。

前天,我在写后端的时候,需要获取到最新的github个人仓库,然后我去搜索了一下,发现github有提供api,格式为https://api.github.com/users/$username/repos?page=1&per_page=6&sort=updated; 后面的参数根据自己需要可以修改,包括数量和时间。返回的是一个json,通过php解析,里面是几个数组,数组里面又是数组。那么我们可以把每个链接对应项目名字提取出来。把他构造成以下形式:

<a href="url" target="_blank"> repo name</a>

首先造一个方法,用于获取github api的返回值。

$repo_name = array();
$repo_url = array();
function get_data($username)
{
    $url = "https://api.github.com/users/" . $username . "/repos?page=1&per_page=6&sort=updated";
    $ch = curl_init();
// 设置URL和相应的选项
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36');
//return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $json_string = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($json_string, true);
    foreach ($data as $each) {
        global $repo_name, $repo_url;
        $repo_name[] = $each['name'];
        $repo_url[] = $each['html_url'];
    }
}

再用其他两个方法来回调repo name和repo url的数组。

function get_repo()
{
    global $repo_name;
    return $repo_name;
}
function get_url()
{
    global $repo_url;
    return $repo_url;
}

调用方法

<?php get_data($this->options->g_name);
$repo_name = get_repo();
$repo_url = get_url();
$all = array();
$all = array_map(function($i1,$i2){
    return '<a href="'.$i1.'" target="_blank">'.$i2.'</a>';
}, $repo_url,$repo_name);
foreach ($all as $item){
   echo '<li>'.$item.'</li>';
}
?>
评论区加载中...