| 方案 | 優點 | 缺點 | 適用場景 |
|---|---|---|---|
| Google Chart API | 零安裝、極簡單行 | 依賴外部服務、有流量限制、中國大陸可能不穩 | 快速原型、內部工具 |
| PHP QR Code 庫 | 純 PHP、離線運作、可自訂 | 效能較低、維護較舊 | 中小專案、需客製化 |
| EndroidQrCodeBundle | Symfony 整合佳、支援 Twig、可快取、設定集中 | 需額外安裝 | 正式 Symfony 專案 |
<?php
function generateQRfromGoogle($chl, $widthHeight = '150', $EC_level = 'L', $margin = '0') {
$url = urlencode($chl);
echo '<img src="https://chart.googleapis.com/chart?chs='.$widthHeight.'x'.$widthHeight.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$url.'" alt="QR Code" />';
}
// 使用
generateQRfromGoogle('https://example.com');
?>
API 文件:Google QR Code API
下載:SourceForge 或官網 phpqrcode.sourceforge.net
<?php
include('./phpqrcode/phpqrcode.php'); // 合併版單檔
// 產生檔案
QRcode::png('code data text', 'filename.png');
// 直接輸出到瀏覽器
QRcode::png('some other text 1234');
?>
composer require endroid/qrcode-bundle
<?php // app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new Endroid\Bundle\QrCodeBundle\EndroidQrCodeBundle(),
);
}
# app/config/routing.yml
EndroidQrCodeBundle:
resource: "@EndroidQrCodeBundle/Controller/"
type: annotation
prefix: /qrcode
endroid_qr_code:
size: 100
padding: 10
extension: gif
error_correction_level: high
foreground_color: { r: 0, g: 0, b: 0, a: 0 }
background_color: { r: 255, g: 255, b: 255, a: 0 }
# label: "My label"
# labelFontSize: 16
{# 一般文字 #}
<img src="{{ qrcode_url(message) }}" />
<img src="{{ qrcode_url(message, extension='png') }}" />
<img src="{{ qrcode_url(message, size=150) }}" />
{# Data URI 內嵌(無需儲存檔案) #}
<img src="{{ qrcode_data_uri(message, size=200, padding=10) }}" />
use Endroid\QrCode\QrCode;
public function qrcodeAction()
{
$qrCode = new QrCode();
$qrCode->setText('https://example.com')
->setSize(200)
->setPadding(10)
->setErrorCorrection('high')
->setForegroundColor(['r' => 0, 'g' => 0, 'b' => 0, 'a' => 0])
->setBackgroundColor(['r' => 255, 'g' => 255, 'b' => 255, 'a' => 0]);
// 回應圖片
return new Response($qrCode->get(), 200, ['Content-Type' => 'image/png']);
// 或儲存檔案
// $qrCode->writeFile(__DIR__.'/../../../web/qrcode.png');
}