To generate a QR code using the Google Chart API in PHP, you can construct the URL for the API and embed it in an image tag. The Google Chart API allows you to create QR codes by passing the necessary data as parameters in the API URL.
Here’s an example of how to generate a QR code for a given text using the Google Chart API in PHP:
<?php
// Function to generate the QR code URL using Google Chart API
function generateQRCode($data, $size = '150x150') {
// Base URL for the Google Chart API
$baseURL = 'https://chart.googleapis.com/chart';
// Parameters for generating the QR code
$params = array(
'cht' => 'qr', // Specifies QR code chart type
'chs' => $size, // Size of the QR code (default: 150x150)
'chl' => urlencode($data) // Data to be encoded in the QR code
);
// Construct the complete URL
$qrCodeURL = $baseURL . '?' . http_build_query($params);
return $qrCodeURL;
}
// Sample text to be encoded in the QR code
$textToEncode = 'Hello, world! This is a QR code example.';
// Generate the QR code URL
$qrCodeURL = generateQRCode($textToEncode);
?>
<!DOCTYPE html>
<html>
<head>
<title>Generate QR Code using Google Chart API</title>
</head>
<body>
<h1>QR Code Example</h1>
<img src="<?php echo $qrCodeURL; ?>" alt="QR Code">
</body>
</html>
In this example, we define a function generateQRCode
that takes the data (text) to be encoded in the QR code and an optional parameter for the size of the QR code. The function constructs the URL for the Google Chart API, passing the necessary parameters.
We then use a sample text Hello, world! This is a QR code example.
as the data to be encoded in the QR code and call the generateQRCode
function to get the URL. The generated QR code is displayed on the webpage using an image tag with the src
attribute set to the QR code URL.
When you open this PHP script in your web browser, it will display the QR code corresponding to the sample text provided in the $textToEncode
variable. You can modify the $textToEncode
variable to encode any other text in the QR code.