Search code examples
phpxmlsimplexml

Nod added into xml as child, wanted sibling (SimpleXMLElement)


I want to add Data2 as a child of Request, but instead it gets added as a child of Data.

class xml{
  public function __construct(){
    $this->request_xml = new SimpleXMLElement("<Request></Request>");
    $this->request_xml->addAttribute('RequestType', "1");
    $this->request_xml->addChild("Data");
    $this->request_xml->addChild("Data2");

    var_dump($this->request_xml->asXml());

  }
}

$object = new xml();

the result is:

<request>
  <data>
    <data2></data2>
  </data>
</request>

I want

<request>
  <data></data>
  <data2></data2>
</request>

What am I missing?

Thanks!


Solution

  • The XML output is:

    <?xml version="1.0"?>
    <Request RequestType="1"><Data/><Data2/></Request>
    

    In other words the Data and Data2 elements are siblings, but short empty tags. If the browser loads it as HTML it will try to repair the missing closing tags. This will not happen if it is parsed as XML. Make sure that you send the correct content type header:

    header('Content-type: application/xml; charset=utf-8');
    

    If you import the SimpleXMLElements into DOM (or better generate the document using DOM in the first place) you get a more options for saving the XML.

    $element = dom_import_simplexml($request_xml);
    echo $element->ownerDocument->saveXml(NULL, LIBXML_NOEMPTYTAG);
    

    Output:

    <?xml version="1.0"?>
    <Request RequestType="1"><Data></Data><Data2></Data2></Request>