php实现github
PHP 实现 GitHub 操作
在 PHP 中实现与 GitHub 的交互,可以通过 GitHub API 或第三方库来完成。以下是几种常见的方法:
使用 GitHub REST API
GitHub 提供了 REST API,可以通过 HTTP 请求直接与 GitHub 进行交互。以下是获取仓库信息的示例代码:
$url = 'https://api.github.com/repos/username/repository';
$options = [
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: PHP',
'Accept: application/vnd.github.v3+json'
]
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$data = json_decode($response, true);
使用 OAuth 进行认证
如果需要访问私有仓库或执行写操作,需要使用 OAuth 进行认证:
$token = 'your_github_token';
$url = 'https://api.github.com/user/repos';
$options = [
'http' => [
'method' => 'GET',
'header' => [
'User-Agent: PHP',
'Authorization: token ' . $token,
'Accept: application/vnd.github.v3+json'
]
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
$repos = json_decode($response, true);
使用第三方库
可以使用 knplabs/github-api 这样的第三方库简化操作。安装方式:
composer require knplabs/github-api php-http/guzzle6-adapter
示例代码:
require 'vendor/autoload.php';
use Github\Client;
$client = new Client();
$client->authenticate('your_github_token', null, Client::AUTH_ACCESS_TOKEN);
$repositories = $client->api('user')->repositories('username');
创建仓库
使用 API 创建新仓库:
$data = [
'name' => 'new-repo',
'description' => 'This is a new repository',
'private' => false
];
$url = 'https://api.github.com/user/repos';
$options = [
'http' => [
'method' => 'POST',
'header' => [
'User-Agent: PHP',
'Authorization: token ' . $token,
'Content-Type: application/json',
'Accept: application/vnd.github.v3+json'
],
'content' => json_encode($data)
]
];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
处理 Webhook
GitHub Webhook 可以用于接收仓库事件通知:
$payload = file_get_contents('php://input');
$data = json_decode($payload, true);
if ($data['action'] === 'opened' && $data['pull_request']) {
// 处理新的 PR
}
以上方法涵盖了 GitHub API 的基本操作,包括读取仓库信息、认证、创建仓库和处理 Webhook。根据具体需求选择合适的实现方式。







