Search code examples
phpxmlsimplexml

PHP Script to generate XML with namespaces and attributes


Thanks for your help, I need php script to generate the following XML

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
  <design xmlns:xlink="http://www.w3.org/1999/xlink" xmlns="http://anydomain.com">
    <name>xxx</name>
  <description>yyy</description>
</design>

Solution

  • You could use SimpleXML to create such xml.

    Rough example:

    $xml = new SimpleXMLElement('<design />'); // set parent node
    $xml->addAttribute('xmlns', 'http://anydomain.com'); // attributes
    $xml->addAttribute('xlink:ns', '', 'http://www.w3.org/1999/xlink');
    
    unset($xml->attributes('xlink', true)['ns']);
    $xml->addChild('name', 'xxx'); // add those children
    $xml->addChild('description', 'yyy');
    echo $xml->asXML(); // output