Reputation: 1270
How can I achieve the below XML DOM structure in PHP?
Could you please help me out with this? Any suggestions, help is much appreciated.
Edit
I have attached the attempted code. It doesn't work & I don't know how I can break that like I've attached above.
Upvotes: 0
Views: 76
Reputation: 383
To create correct XML file you must declare elements as namespaces:
$employees = array();
$employees[] = array('name' => 'Albert', 'age' => 34, 'salary' => 10000, 'lname' => 'Vidula');
$dom = new DOMDocument('1.0', 'utf-8');
$domEmployees = $dom->createElement('employees');
foreach($employees as $employee)
{
$domEmployee = $dom->createElement('employee');
$domEmployee->appendChild($dom->createElementNS('http://www.w3.org/1999/xhtml', 'name:fname', $employee['name']));
$domEmployee->appendChild($dom->createElementNS('http://www.w3.org/1999/xhtml', 'name:lname', $employee['lname']));
$domEmployee->appendChild($dom->createElement('age', $employee['age']));
$domEmployee->appendChild($dom->createElement('salary', $employee['salary']));
$domEmployees->appendChild($domEmployee);
}
$dom->appendChild($domEmployees);
echo $dom->saveXML();
Outputs:
<?xml version="1.0" encoding="utf-8"?>
<employees xmlns:name="http://www.w3.org/1999/xhtml">
<employee xmlns:name="http://www.w3.org/1999/xhtml">
<name:fname xmlns:name="http://www.w3.org/1999/xhtml">Albert</name:fname>
<name:lname xmlns:name="http://www.w3.org/1999/xhtml">Vidula</name:lname>
<age>34</age>
<salary>10000</salary>
</employee>
</employees>
Upvotes: 1
Reputation: 11562
This is not how it works:
$doc->createElement("name:lname");
The element's name is actually lname
and name
is the handle of the namespace, which you must have defined somewhere. Then you need to use createElementNS() instead.
Upvotes: 1