With the rapid development of internet technology, QR codes have become an essential tool for information transmission. They not only store a large amount of information but can also be scanned and recognized quickly. As a result, QR codes have been widely applied in various industries. In many cases, we need to batch generate QR codes, such as for product labels, event tickets, etc.
PHP, as a popular scripting language, is flexible and easy to use, making it ideal for developing QR code generation tools. In this article, we will explain how to use PHP to batch generate QR codes and provide example code to help developers understand and practice.
To generate QR codes, we need an external library. In this example, we use the widely-used open-source library PHP QR Code. You can download the library from the PHP QR Code website and include it in your code.
Next, we will show you how to write PHP code to batch generate QR codes. In the code below, we will generate 100 QR codes and save them to a specified directory, with filenames like "qrcode_1.png", "qrcode_2.png", and so on.
<?php require('phpqrcode/qrlib.php'); $quantity = 100; // Number of QR codes to generate $path = './qrcodes/'; // QR code save directory // Create QR code save directory if (!is_dir($path)) { mkdir($path, 0777, true); } for ($i = 1; $i <= $quantity; $i++) { $data = "https://example.com/qrcode/{$i}"; // Content for the QR code $filename = $path . "qrcode_{$i}.png"; // QR code save filename // Generate QR code QRcode::png($data, $filename, QR_ECLEVEL_L, 8, 2); echo "QR Code {$i} generated successfully!<br>"; } echo "Batch QR code generation complete!"; ?>
In the code above, we use the "require" function to include the main PHP QR Code library file (qrlib.php). Then, we define the number of QR codes to generate ($quantity) and specify the directory where the QR codes will be saved ($path). We use the "mkdir" function to create the save directory if it doesn't already exist. Next, we use a "for" loop to generate 100 QR codes, each containing a different URL, with "$i" used to generate a unique QR code number. Finally, we call the "QRcode::png" function to generate each QR code and save it as a PNG file in the specified directory.
After running the code, you will find 100 QR code files generated in the specified directory, and success messages displayed in the browser. These QR code files can be modified as needed, such as generating QR codes based on data from a database or adding custom styles to the QR codes.
This article covered how to use PHP to generate QR codes in batch, providing code examples to help you get started. With this method, you can quickly generate large numbers of QR codes for various applications. You can also adjust the code to fit your needs, such as integrating database data for QR code generation or adding custom styles.