首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 生成二維碼的兩種主流方案:Google API 與 PHP QR Code 庫完整指南

     編輯:PHP 綜合知識

前言

二維碼已成為行銷、支付、分享等場景的標準工具。PHP 開發者常用的生成方案有兩種:呼叫 Google Chart API(現已停止服務,僅供參考)與使用本地端 PHP QR Code 庫。本文詳細說明兩種做法的完整代碼與參數設定。

方案一:Google Chart API(歷史參考)

1. GET 請求方式

透過組合 URL 參數直接輸出 <img> 標籤:

function generateQRfromGoogle($data, $widhtHeight = '150', $EC_level = 'L', $margin = '0') {
    $url = urlencode($data);
    echo '<img src="https://chart.apis.google.com/chart?chs=' . $widhtHeight . 'x' . $widhtHeight 
        . '&cht=qr&chld=' . $EC_level . '|' . $margin . '&chl=' . $data 
        . '" width="' . $widhtHeight . '" height="' . $widhtHeight . '"/>';
}

參數說明:

  • chs:圖片尺寸(寬x高)
  • chld:錯誤修正等級(L/M/Q/H)與邊距
  • chl:編碼內容(需 URL-encoded)

2. POST 請求方式(適合大量資料)

使用 cURL 發送 POST 請求,回傳二進位圖片資料:

function qrcode($width, $height, $string) {
    $post_data = [
        'cht' => 'qr',
        'chs' => $width . 'x' . $height,
        'chl' => $string,
        'choe' => 'UTF-8'
    ];
    $url = 'https://chart.apis.google.com/chart';
    $data = http_build_query($post_data);
    
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_POST => 1,
        CURLOPT_HEADER => 0,
        CURLOPT_URL => $url,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_RETURNTRANSFER => 1
    ]);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result; // 回傳二進位 PNG
}

使用範例:

header('Content-Type: image/png');
echo qrcode(300, 300, '版權所有:https://www.example.com');

方案二:PHP QR Code 庫(推薦,離線可用)

1. 安裝與引入

下載地址:phpqrcode.sourceforge.net
解壓後引入核心檔案:

include './phpqrcode.php';

2. 基本生成代碼

$data = '版權所有:https://www.example.com';
$errorCorrectionLevel = 'L'; // L/M/Q/H
$matrixPointSize = 4;        // 模組大小(像素)
QRcode::png($data, false, $errorCorrectionLevel, $matrixPointSize);

參數對照:

參數說明範例值
$data編碼內容字串
$outfile輸出檔案路徑,false 直接輸出瀏覽器false / 'qrcode.png'
$errorCorrectionLevel錯誤修正等級L(7%) M(15%) Q(25%) H(30%)
$matrixPointSize每個模組像素大小1~10
$margin邊距模組數0~10

進階應用:儲存檔案與自訂 Logo

若需儲存檔案,指定第二參數為路徑:

QRcode::png($data, 'qrcode.png', 'H', 6, 2);

加入 Logo 需結合 GD 库處理圖片合成,可參考庫內 examples 目錄範例。

總結

  • Google API 簡單但依賴外部服務,且已停止維護。
  • PHP QR Code 為純 PHP 實現,無外部依賴,適合生產環境。
  • 建議採用 PHP QR Code,並搭配 Composer 管理依賴(chillerlan/php-qrcode 為現代替代方案)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved