##概要
・github APIを利用してJSONを取得、ダウンロード数を抽出・合計して表示
・スクリプトで呼び出して表示
1.download_counter.php をサーバー内に設置
<?php
// レスポンスを JSON として返す
header("Content-Type: application/json; charset=UTF-8");
// GitHub API の URL
$url = "https://api.github.com/repos/donaco/KanColleViewer/releases";
// cURL を使って安定的に取得
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, "MyApp"); // User-Agent 必須
$response = curl_exec($ch);
if ($response === false) {
echo json_encode(["error" => curl_error($ch)]);
curl_close($ch);
exit;
}
curl_close($ch);
// JSON を配列に変換
$data = json_decode($response, true);
if ($data === null) {
echo json_encode(["error" => "JSON decode failed"]);
exit;
}
// download_count の合計を計算
$total = 0;
foreach ($data as $release) {
if (isset($release["assets"])) {
foreach ($release["assets"] as $asset) {
if (isset($asset["download_count"])) {
$total += $asset["download_count"];
}
}
}
}
// 結果を JSON で返す
echo json_encode(["total_downloads" => $total]);
2.JSON が取得できるか確認
curl http://あなたのサーバ/download_counter.php
この様に返答があればOK
{ "total_downloads": 9999 }
3.html 内に埋め込み
<h1>総ダウンロード数: <span id="downloads"></span></h1>
<script>
fetch("cnt.php")
.then(res => res.json())
.then(data => {
document.getElementById("downloads").textContent = data.total_downloads;
})
.catch(err => {
console.error("API取得エラー:", err);
});
</script>