You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过GitHub API在PHP中获取私有仓库的临时下载链接?

解决GitHub API获取私有仓库归档链接及乱码问题

问题原因

你当前调用的/repos/{owner}/{repo}/zipball接口直接返回的是ZIP文件的二进制内容,并非JSON或文本格式,所以直接输出会显示乱码。若需要临时下载链接,需捕获接口返回的重定向地址。

解决方案

1. 获取临时下载链接

修改cURL配置,禁用自动跟随重定向,手动解析响应头中的Location字段获取临时链接:

$token = 'abcdef';
$url   = 'https://api.github.com/repos/meiuser/ai/zipball';
$ch    = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); // 禁用自动跳转
curl_setopt($ch, CURLOPT_HEADER, true); // 包含响应头信息
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
    'X-GitHub-Api-Version: 2022-11-28',
    'User-Agent: ai'
]);

$response = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$headers = substr($response, 0, $header_size);

// 提取Location头中的临时下载链接
preg_match('/Location: (.*)\r\n/', $headers, $matches);
if (isset($matches[1])) {
    $temp_download_url = $matches[1];
    echo "临时下载链接:" . $temp_download_url;
}

curl_close($ch);

2. 直接保存ZIP文件(若无需链接,只需归档文件)

如果不需要获取链接,而是直接将私有仓库归档保存到本地,可直接处理二进制响应:

$token = 'abcdef';
$url   = 'https://api.github.com/repos/meiuser/ai/zipball';
$ch    = curl_init();
$fp = fopen('repo_archive.zip', 'w'); // 本地保存路径

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Authorization: Bearer ' . $token,
    'X-GitHub-Api-Version: 2022-11-28',
    'User-Agent: ai'
]);

curl_exec($ch);

curl_close($ch);
fclose($fp);

关键注意事项

  • 移除了Accept: application/vnd.github+json请求头,因为该接口返回的是二进制文件,而非GitHub指定的JSON格式,保留该头会导致响应异常。
  • 临时下载链接有效期较短(通常数分钟),仅适合即时使用。
  • 确保你的Personal Access Token拥有repo权限,能够访问目标私有仓库。

内容的提问来源于stack exchange,提问作者user23296141

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 07:57:47