Current Location: Home> Latest Articles> PHP Form Export Tutorial: Export Data to CSV, JSON, XML, or Database Easily

PHP Form Export Tutorial: Export Data to CSV, JSON, XML, or Database Easily

M66 2025-10-28

Complete Guide to Exporting Forms in PHP

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.

Create an HTML Form

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>

Process Form Data with PHP

In the export.php file, use the $_POST superglobal to retrieve the form data:

$name = $_POST['name'];
$email = $_POST['email'];

Different Ways to Export Data

Depending on your project’s needs, you can choose from several export options.

Export to CSV File

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);

Export to JSON File

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);

Export to XML File

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');

Save Data into a Database

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();

Provide File Download to the User

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');

Conclusion

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.