php获取最新github仓库

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$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的数组。

1
2
3
4
5
6
7
8
9
10
function get_repo()
{
global $repo_name;
return $repo_name;
}
function get_url()
{
global $repo_url;
return $repo_url;
}

调用方法

1
2
3
4
5
6
7
8
9
10
11
<?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>';
}
?>

本文标题:php获取最新github仓库

文章作者:yiny

发布时间:2019年03月31日 - 09:03

最后更新:2019年03月31日 - 10:03

原始链接:https://blog.yiny.ml/2019/03/31/php获取最新github仓库/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%