1. First Create your File XML with createxmlExample.php and running it in the browser
<?php
$xml= new DomDocument("1.0","UTF-8");
$xml->formatOutput=true;
$xml->preserveWhiteSpace=false;
$company=$xml->createElement("company");
$company=$xml->createElement("company");
$xml->appendChild($company);
$employee=$xml->createElement("employee");
$company->appendChild($employee);
$name=$xml->createElement("name","John");
$employee->appendChild($name);
$age=$xml->createElement("age",25);
$employee->appendChild($age);
$department=$xml->createElement("department","computer");
$employee->appendChild($department);
echo "<xmp>".$xml->saveXML()."</xmp>";
$xml->save("company.xml");
?>
2. Create a HTML form with a form as you need in your project
form.html
<html>
<head>
<title>Storing Dynamic data to a xml</title>
</head>
<body>
<form method="post" action="writeToXML.php">
Name :<input type="text" name="name" placeholder="Name" />
Age :<input type="number" name="age" placeholder="age" />
Department :<input type="text" name="dept" placeholder="Department" />
<input type="submit" name="submit" value="ok">
</form>
</body>
</html>
3. Now create the action page which writes data into XML file
writeToXML.php
<?php
$xml= new DomDocument("1.0","UTF-8");
$xml->formatOutput=true;
$xml->preserveWhiteSpace=false;
$xml->load("company.xml");
if (!$xml) {
$company=$xml->createElement("company");
$xml->appendChild($company);
}
else
{
$company=$xml->firstChild;
}
if (isset($_POST['submit'])) {
$fname=$_POST['name'];
$fage=$_POST['age'];
$fdept=$_POST['dept'];
$employee=$xml->createElement("employee");
$company->appendChild($employee);
$name=$xml->createElement("name",$fname);
$employee->appendChild($name);
$age=$xml->createElement("age",$fage);
$employee->appendChild($age);
$department=$xml->createElement("department",$fdept);
$employee->appendChild($department);
echo "<xmp>".$xml->saveXML()."</xmp>";
$xml->save("company.xml");
}
?>
4. Now check the Output by opening the xml file
company.xml
Now you can see parsed data from the html for have written in the XML file.
<?xml version="1.0" encoding="UTF-8"?>
<company>
<employee>
<name>John</name>
<age>25</age>
<dept>computer</dept>
</employee>
<employee>
<name>Kevin</name>
<age>45</age>
<dept>IOT</dept>
</employee>
<employee>
<name>Alan</name>
<age>34</age>
<dept>Management</dept>
</employee>
</company>
No comments:
Post a Comment