Search code examples
phpnamespacessimplexml

PHP SimpleXMLElement addAttribute namespaces syntax


I'm working with SimpleXMLElement for the first time and need to generate a line in my XML as follows:

<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">

I haven't used addAttribute with namespaces before and can't get the correct syntax working here - I've started with this:

$node = new SimpleXMLElement('< Product ></Product >');
$node->addAttribute("xmlns:", "xsd:", 'http://www.w3.org/2001/XMLSchema-instance'); 

but can't work out how to correct this for the appropriate syntax to generate the desired output?


Solution

  • solution 1: add a prefix to the prefix

    <?php
    $node = new SimpleXMLElement('<Product/>');
    $node->addAttribute("xmlns:xmlns:xsi", 'http://www.w3.org/2001/XMLSchema-instance');
    $node->addAttribute("xmlns:xmlns:xsd", 'http://www.w3.org/2001/XMLSchema');
    echo $node->asXML();
    

    output:

    <?xml version="1.0"?>
    <Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>
    

    note: this is a workaround and actually doesn't set the namespace for the attribute, but just quite enough if you are going to echo / save to file the result

    solution 2: put namespace directly in the SimpleXMLElement constructor

    <?php
    $node = new SimpleXMLElement('<Product xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>');
    echo $node->asXML();
    

    output is the same as in solution 1

    solution 3 (adds additional attribute)

    <?php
    $node = new SimpleXMLElement('<Product/>');
    $node->addAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance", "xmlns");
    $node->addAttribute("xmlns:xsd", 'http://www.w3.org/2001/XMLSchema', "xmlns");
    echo $node->asXML();
    

    output adds additional xmlns:xmlns="xmlns"

    <?xml version="1.0"?>
    <Product xmlns:xmlns="xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"/>