Skip to content

How to create an XML with multiple root?


I want to create an XML sample like below:

<company>

<agents>
<name></name>
<address></address>
</agents>

<employees>
<name></name>
<address></address>
</employees>

</company>

Is this possible? If it’s possible, how?
the code I used is the one below:
// create root node
$root = $doc->createElement(‘customer’);
$root = $doc->appendChild($root);
// process one row at a time
while($row = mysql_fetch_array($dbresult,MYSQL_ASSOC)) {
// add node for each row
$occ = $doc->createElement($table_id);
$occ = $root->appendChild($occ);
// add a child node for each field
foreach ($row as $fieldname => $fieldvalue) {
$child = $doc->createElement($fieldname);
$child = $occ->appendChild($child);
$value = $doc->createTextNode($fieldvalue);
$value = $child->appendChild($value);
} // foreach
} // while
// get completed xml document
$xml_string = $doc->saveXML();
//echo $xml_string;
$filenamepath .= "customer.xml";
$fp = fopen($filenamepath,’w');
$write = fwrite($fp,$xml_string);

Please Help! Thank you!


One Comment

  1. TheMadProfessor wrote:

    Instead of two child nodes, why not a single one with an attribute?
    <company>
    <person role=’employee’>
    <name></name>
    <address></address>
    </person>
    <person role=’agent’>
    <name></name>
    <address></address>
    </person>
    <person role=’employee’>
    <name></name>
    <address></address>
    </person>
    </company>

    Thursday, January 21, 2010 at 9:22 am | Permalink

Post a Comment

Your email is never published nor shared.