You can generate an XML or JSON file from the submitted form data using PHP. Here’s how to create both:
1. Generating JSON
You can collect form data and convert it into a JSON format using PHP’s json_encode function.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Collect form data
$formData = [
"name" => $_POST["name"] ?? "",
"password" => $_POST["password"] ?? "",
"email" => $_POST["email"] ?? "",
"website" => $_POST["website"] ?? "",
"age" => $_POST["age"] ?? "",
"gender" => $_POST["gender"] ?? "",
"hobbies" => $_POST["hobbies"] ?? [],
"country" => $_POST["country"] ?? "",
"birthday" => $_POST["birthday"] ?? "",
];
// Convert to JSON
$jsonData = json_encode($formData, JSON_PRETTY_PRINT);
// Save to a file
file_put_contents("form_data.json", $jsonData);
// Output message
echo "<p>Form data has been saved to <strong>form_data.json</strong></p>";
}
?>
2. Generating XML
To create an XML file, you can use PHP’s SimpleXMLElement.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Create the XML structure
$xml = new SimpleXMLElement('<formData/>');
// Add form data to XML
$xml->addChild("name", htmlspecialchars($_POST["name"] ?? ""));
$xml->addChild("password", htmlspecialchars($_POST["password"] ?? ""));
$xml->addChild("email", htmlspecialchars($_POST["email"] ?? ""));
$xml->addChild("website", htmlspecialchars($_POST["website"] ?? ""));
$xml->addChild("age", htmlspecialchars($_POST["age"] ?? ""));
$xml->addChild("gender", htmlspecialchars($_POST["gender"] ?? ""));
$hobbies = $xml->addChild("hobbies");
if (!empty($_POST["hobbies"])) {
foreach ($_POST["hobbies"] as $hobby) {
$hobbies->addChild("hobby", htmlspecialchars($hobby));
}
}
$xml->addChild("country", htmlspecialchars($_POST["country"] ?? ""));
$xml->addChild("birthday", htmlspecialchars($_POST["birthday"] ?? ""));
// Save to a file
$xml->asXML("form_data.xml");
// Output message
echo "<p>Form data has been saved to <strong>form_data.xml</strong></p>";
}
?>
Steps to Use in Your Form
- Save one of the above PHP snippets (for JSON or XML) in
submit_form.php. - When the form is submitted, the script will create either
form_data.jsonorform_data.xmlin the server’s directory. - The user will see a success message after submission.
Let me know if you need further assistance!