PHP で Google Books API
vi で 10 分クオリティ
コンソールで ISBN(ハイフン無し)を受け取って雑に書籍情報を返すスクリプト
code:php
<?php
$base = 'https://www.googleapis.com/';
$path = 'books/v1/volumes';
echo "ISBN コードを入力してください: ";
$handle = fopen("php://stdin", "r");
$line = fgets($handle);
$isbn = trim($line);
if (empty($isbn)) {
echo "不正な入力\n";
exit(2);
}
$response = file_get_contents(
$url = $base . $path . "?" . http_build_query('q' => "isbn:{$isbn}"),
);
$json = json_decode($response, true);
if (($json'totalItems' ?? 0) === 0) {
echo "書籍情報が見つかりませんでした\n";
exit(1);
}
$book = Book::fromArray($json);
var_dump($book);
class Book {
public function __construct(
public string $title,
public array $authors,
public string $publisher,
public string $publishedDate,
){}
public static function fromArray(array $data): self
{
// google books api のレスポンス前提
return new self(
title: $data"items"0"volumeInfo""title" ?? '',
authors: $data"items"0"volumeInfo""authors" ?? [],
publisher: $data"items"0"volumeInfo""publisher" ?? '',
publishedDate: $data"items"0"volumeInfo""publishedDate" ?? '',
);
}
}