C:blanc
投稿日
2022年07月08日
Blog PHP

PHPでQRCodeを生成する

  • このエントリーをはてなブックマークに追加

ライブラリー

QRコードを生成するには、PHPのライブラリー chillerlan/php-qrcode を使えば簡単です。

インストール

Composer で php-qrcode をインストールします。

composer install
composer.json
{
    "require": {
        "php": "^8.0",
        "chillerlan/php-qrcode": "dev-main"
    }
}

PHPコード

8行目で出力する画像タイプを指定します。
今回はSVGにしました。
その他のオプションはこちら
PHP
<?php
require_once __DIR__ . '/vendor/autoload.php';
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use chillerlan\QRCode\Common\EccLevel;

$options = new QROptions([
    'outputType' => QRCode::OUTPUT_MARKUP_SVG,
    'eccLevel' => EccLevel::L,
]);

$url = 'https://blog.c-blanc.com/';
$img = (new QRCode($options))->render($url);
?>

<div><img src="<?= $img ?>" width="300" height="300" /></div>

DEMO

保存→ダウンロード

サーバー上に保存して、ダウンロードできるようにしてみました。
PHP
<?php
require_once __DIR__ . '/vendor/autoload.php';
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use chillerlan\QRCode\Common\EccLevel;

$options = new QROptions([
    'outputType' => QRCode::OUTPUT_MARKUP_SVG,
    'eccLevel' => EccLevel::L,
]);

$url = 'https://blog.c-blanc.com/';
$file = 'data/qrcode.svg';
$path = __DIR__ . '/' . $file;

(new QRCode($options))->render($url, $path);
?>

<div><img src="<?= $file ?>" width="300" height="300" /></div>
<div><a href="<?= $file ?>" download>ダウンロード</a></div>

終わりに

もっと複雑なQRコードも作れるみたいですが、これくらいで十分だと思います。
また、ダウンロードすれば、そのままベクターデータとしてAdobe Illustratorなどでも利用できます。

PROFILE

C:blanc
フリーランスのプログラマーです。
  • COMMENT

    送信しました! コメントは承認後表示されます!
  • あと150文字