二維碼已成為行銷、支付、分享等場景的標準工具。PHP 開發者常用的生成方案有兩種:呼叫 Google Chart API(現已停止服務,僅供參考)與使用本地端 PHP QR Code 庫。本文詳細說明兩種做法的完整代碼與參數設定。
透過組合 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)使用 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');
下載地址:phpqrcode.sourceforge.net
解壓後引入核心檔案:
include './phpqrcode.php';
$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 |
若需儲存檔案,指定第二參數為路徑:
QRcode::png($data, 'qrcode.png', 'H', 6, 2);
加入 Logo 需結合 GD 库處理圖片合成,可參考庫內 examples 目錄範例。
chillerlan/php-qrcode 為現代替代方案)。