Search code examples
phpxmlsimplexmlparent-child

PHP SimpleXML - Multiple children with same name


I am currently generating an xml file with the following php code. It takes form inputs and puts them into an xml file.

I am wanting to have multiple children with the same name. Eg:

<person>
  <address>
    <street>streetname</street>
    <streetnumber>streetnumber</streetnumber>
  </address>
  <address>
    <street>streetname</street>
    <streetnumber>streetnumber</streetnumber>
  </address>
</person>  

My code to generate the xml follows this structure;

//Add first address - working

$xml->person = "";
$xml->person->address = "";

$xml->person->address->addChild('streetname', $_POST['streetname1']);
$xml->person->address->addChild('streetnumber', $_POST['streetnumber1']);


//Attempt to add second address, doesn't work

$xml->person->address = "";

$xml->person->address->addChild('streetname', $_POST['streetname2']);
$xml->person->address->addChild('streetnumber', $_POST['streetnumber2']);

Solution

  • It's much easier and less verbose to use variables when building your XML document. Then you can add multiple <address> elements to your <person> element like this...

    $person = $xml->addChild('person');
    
    $address1 = $person->addChild('address');
    $address1->addChild('streetname', $_POST['streetname1']);
    $address1->addChild('streetnumber', $_POST['streetnumber1']);
    
    $address2 = $person->addChild('address');
    $address2->addChild('streetname', $_POST['streetname2']);
    $address2->addChild('streetnumber', $_POST['streetnumber2']);