0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Github リリースの総ダウンロード数をWeb上に表示

0
Last updated at Posted at 2025-12-30

##概要
・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>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?