In this article we will learn how to send website data to google sheet in the most simplest way.
Step 1: Create a Google Form
- Create a new Google Form.
- Add fields that you want to populate from your PHP script. For example, let’s say you have two fields: “Name” and “Email”.
Step 2: Get Form URL and Field IDs
- Once your form is ready, click on the three dots in the upper-right corner and choose “Get pre-filled link”.
- Fill in some sample data and click “Get Link”.
- The generated link will have the field IDs you need. It will look something like this:
https://docs.google.com/forms/d/e/[FORM_ID]/formResponse?entry.[FIELD_ID_1]=sampleName&entry.[FIELD_ID_2]=sampleEmail
Step 3: PHP Code
Here’s a simple PHP code snippet to send data to Google Sheets using cURL:
<?php
// Google Form URL
$formUrl = 'https://docs.google.com/forms/d/e/[FORM_ID]/formResponse';
// Data to be sent
$data = [
'entry.[FIELD_ID_1]' => 'John',
'entry.[FIELD_ID_2]' => 'john@example.com'
];
// Initialize cURL
$ch = curl_init();
// cURL settings
curl_setopt($ch, CURLOPT_URL, $formUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL
$result = curl_exec($ch);
// Close cURL
curl_close($ch);
// Output the result (for debugging)
echo $result;
?>
Replace [FORM_ID]
, [FIELD_ID_1]
, and [FIELD_ID_2]
with your actual Form ID and Field IDs.
Full Source Code is Written Below
Google.php Page
<?php
$name = $_POST['name'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
if (isset($_POST['submit'])) {
// Google Form URL
$formUrl = 'https://docs.google.com/forms/d/e/1FAIpQLSfFOl9BfdtdVHf_hcqe69ZwLKQ6GHWSeDJPaFP9d-2v20FA_Q/formResponse';
// Data to be sent
$data = [
'entry.1027832668' => "$name",
'entry.547919694' => "$mobile",
'entry.981977111' => "$email"
];
// Initialize cURL
$ch = curl_init();
// cURL settings
curl_setopt($ch, CURLOPT_URL, $formUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute cURL
$result = curl_exec($ch);
// Close cURL
curl_close($ch);
// Output the result (for debugging)
//echo $result;
header("Location: thankyou.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Simple Form</title>
</head>
<body>
<form method="POST">
<input type="text" name="name">
<br>
<input type="text" name="email">
<br>
<input type="text" name="mobile">
<br>
<button name="submit">Submit form</button>
</form>
</body>
</html>
Thankyou.php Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Thank you</title>
</head>
<body>
Thank you
</body>
</html>