萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 根據 ISBN 查詢 Amazon 圖書信息:完整實現與現代替代方案

原始實現分析(HTML 解析脆弱)

原代碼通過 file_get_contents 抓取 Amazon 手機版頁面,用字串搜尋 <meta name="description" content="Amazon: 提取標題,用 ecx.images-amazon.com 提取封面圖。極度依賴頁面結構,Amazon 任意改版即失效。

現代最佳實踐:Product Advertising API (PA-API 5.0)

官方 API 提供結構化 JSON、簽名驗證、配額管理、圖片多尺寸、價格/庫存/評價等豐富數據。

前置準備

  1. 註冊 Amazon Associates 並獲得 Access Key/Secret Key/Partner Tag
  2. 啟用 PA-API 5.0(需近 30 天有推薦銷售)
  3. 安裝 SDK:composer require aws/aws-sdk-php(含 PA-API 客戶端)

完整查詢範例

<?php
require 'vendor/autoload.php';

use Aws\Api\Service;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;
use Aws\Signature\SignatureProvider;
use Aws\Credentials\Credentials;

function searchAmazonByISBN(string $isbn, string $accessKey, string $secretKey, string $partnerTag, string $region = 'us-east-1'): ?array {
    $endpoint = "https://webservices.amazon.$region/paapi5/searchitems";
    
    $payload = [
        'PartnerTag'      => $partnerTag,
        'PartnerType'     => 'Associates',
        'Marketplace'     => 'www.amazon.com',
        'Keywords'        => $isbn,
        'SearchIndex'     => 'Books',
        'ItemCount'       => 1,
        'Resources'       => [
            'ItemInfo.Title',
            'Images.Primary.Large',
            'Offers.Listings.Price',
            'Offers.Listings.Availability',
            'BrowseNodeInfo.BrowseNodes',
        ],
    ];

    $httpClient = new Client();
    $credentials = new Credentials($accessKey, $secretKey);
    $signatureProvider = SignatureProvider::create('ProductAdvertisingAPI', $region, $credentials);

    $request = new \GuzzleHttp\Psr7\Request('POST', $endpoint, [
        'Content-Type' => 'application/json',
        'Host'         => "webservices.amazon.$region",
        'X-Amz-Target' => 'com.amazon.paapi5.v1.ProductAdvertisingAPIv1.SearchItems',
    ], json_encode($payload));

    $signedRequest = $signatureProvider->signRequest($request);
    $response = $httpClient->send($signedRequest);
    $data = json_decode($response->getBody()->getContents(), true);

    if (empty($data['SearchResult']['Items'])) return null;
    $item = $data['SearchResult']['Items'][0];
    
    return [
        'asin'      => $item['ASIN'] ?? null,
        'title'     => $item['ItemInfo']['Title']['DisplayValue'] ?? null,
        'image'     => $item['Images']['Primary']['Large']['URL'] ?? null,
        'price'     => $item['Offers']['Listings'][0]['Price']['DisplayAmount'] ?? null,
        'currency'  => $item['Offers']['Listings'][0]['Price']['Currency'] ?? 'USD',
        'url'       => "https://www.amazon.com/dp/{$item['ASIN']}?tag=$partnerTag",
    ];
}

// 使用
$result = searchAmazonByISBN('9787115428028', 'AK...', 'SK...', 'yourtag-20');
if ($result) {
    echo "《{$result['title']}》\n";
    echo "封面: {$result['image']}\n";
    echo "價格: {$result['price']} {$result['currency']}\n";
    echo "鏈接: {$result['url']}\n";
} else {
    echo "未找到\n";
}

免費替代方案(無需 API 密鑰)

1. Open Library API(開放、無需 Key)

<?php
function searchOpenLibrary(string $isbn): ?array {
    $url = "https://openlibrary.org/api/books?bibkeys=ISBN:$isbn&format=json&jscmd=data";
    $data = @file_get_contents($url);
    if (!$data) return null;
    $json = json_decode($data, true);
    $key = "ISBN:$isbn";
    if (empty($json[$key])) return null;
    $book = $json[$key];
    return [
        'title'  => $book['title'] ?? null,
        'authors'=> array_column($book['authors'] ?? [], 'name'),
        'cover'  => $book['cover']['large'] ?? ($book['cover']['medium'] ?? null),
        'publish_date' => $book['publish_date'] ?? null,
        'url'    => "https://openlibrary.org/isbn/$isbn",
    ];
}

2. Google Books API(免費配額大)

<?php
function searchGoogleBooks(string $isbn, string $apiKey = ''): ?array {
    $url = "https://www.googleapis.com/books/v1/volumes?q=isbn:$isbn";
    if ($apiKey) $url .= "&key=$apiKey";
    $data = @file_get_contents($url);
    if (!$data) return null;
    $json = json_decode($data, true);
    if (empty($json['items'])) return null;
    $info = $json['items'][0]['volumeInfo'];
    return [
        'title'       => $info['title'] ?? null,
        'authors'     => $info['authors'] ?? [],
        'cover'       => $info['imageLinks']['thumbnail'] ?? null,
        'published'   => $info['publishedDate'] ?? null,
        'description' => $info['description'] ?? null,
        'url'         => $info['infoLink'] ?? null,
    ];
}

3. ISBNdb / OpenBD / 國圖 API

  • ISBNdb:商業 API,免費層 500 次/天
  • OpenBD:日本圖書開放數據
  • 國家圖書館/各國 ISBN 機構通常提供查詢介面

舊版 HTML 解析的健壯化(若必須用)

<?php
function scrapeAmazonFallback(string $isbn): ?array {
    $url = "https://www.amazon.com/dp/$isbn";
    $html = @file_get_contents($url, false, stream_context_create([
        'http' => ['header' => "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36\r\nAccept-Language: en-US,en;q=0.9"]
    ]));
    if (!$html) return null;

    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($html);
    libxml_clear_errors();
    $xpath = new DOMXPath($dom);

    $title = $xpath->query('//span[@id="productTitle"]')->item(0)?->textContent ?? null;
    $image = $xpath->query('//img[@id="landingImage"]')->item(0)?->getAttribute('src') ?? 
             $xpath->query('//div[@id="img-canvas"]//img')->item(0)?->getAttribute('src') ?? null;
    
    return $title ? ['title' => trim($title), 'image' => $image, 'url' => $url] : null;
}

關鍵改進:使用 DOMDocument + DOMXPath 替代字串搜尋,對結構變化更具彈性;設置真實 User-Agent 降低被封風險。

ISBN 格式驗證與轉換

<?php
function normalizeISBN(string $isbn): ?string {
    $isbn = preg_replace('/[-\s]/', '', $isbn);
    if (strlen($isbn) === 10) {
        // ISBN-10 驗證碼計算
        $sum = 0;
        for ($i = 0; $i < 9; $i++) $sum += (int)$isbn[$i] * (10 - $i);
        $check = $sum % 11;
        $checkChar = $check === 10 ? 'X' : (string)$check;
        if ($isbn[9] !== $checkChar) return null;
        // 轉 ISBN-13
        return '978' . substr($isbn, 0, 9) . calculateISBN13Check('978' . substr($isbn, 0, 9));
    }
    if (strlen($isbn) === 13 && ctype_digit($isbn)) {
        // ISBN-13 驗證
        $sum = 0;
        for ($i = 0; $i < 12; $i++) $sum += (int)$isbn[$i] * ($i % 2 === 0 ? 1 : 3);
        return ($sum % 10 === 0) ? $isbn : null;
    }
    return null;
}
function calculateISBN13Check(string $prefix12): string {
    $sum = 0;
    for ($i = 0; $i < 12; $i++) $sum += (int)$prefix12[$i] * ($i % 2 === 0 ? 1 : 3);
    return (string)((10 - $sum % 10) % 10);
}

建議:優先使用官方 PA-API 或免費開放 API;HTML 解析僅作最後備援並加強錯誤處理。ISBN 輸入務必先標準化驗證,避免無效查詢浪費配額。

copyright © 萬盛學電腦網 all rights reserved