Exporting form data is a common requirement in web development, such as saving user-submitted information, generating reports, or creating backups. This guide will show you how to use PHP to export form data into multiple formats including CSV, JSON, XML files, or directly into a database.
First, you need a simple HTML form to collect user input:
<form action="export.php" method="post"> <input type="text" name="name" placeholder="Name"> <input type="email" name="email" placeholder="Email"> <input type="submit" value="Export"> </form>
In the export.php file, use the $_POST superglobal to retrieve the form data:
$name = $_POST['name']; $email = $_POST['email'];
Depending on your project’s needs, you can choose from several export options.
Use PHP’s built-in file functions to create a CSV file:
$fh = fopen('export.csv', 'w');
fputcsv($fh, array('Name', 'Email'));
fputcsv($fh, array($name, $email));
fclose($fh);JSON is a lightweight data format commonly used for data exchange between frontend and backend:
$data = array('name' => $name, 'email' => $email);
$json = json_encode($data);
file_put_contents('export.json', $json);To export the data as XML, use the SimpleXMLElement class:
$xml = new SimpleXMLElement('<data></data>');
$xml->addChild('name', $name);
$xml->addChild('email', $email);
$xml->asXML('export.xml');If you want to store the submitted data permanently, insert it into a database:
$servername = "localhost";
$username = "root";
$password = "";
$database = "form_data";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO users (name, email) VALUES (?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ss", $name, $email);
$stmt->execute();
$conn->close();If you want users to download the exported file automatically, you can set the appropriate headers:
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=export.csv');
readfile('export.csv');By following these methods, you can easily implement form data export functionality in PHP. Whether you’re exporting to CSV, JSON, XML, or storing data in a database, these techniques provide flexibility for various web application needs. Mastering them will greatly enhance your efficiency in handling and exporting data with PHP.