0

I have the following code

    $dom = new DOMDocument('1.0', 'utf-8');        
    $headerNS = $dom->createElementNS('http://somenamespace', 'ttauth:authHeader');
    $accesuser = $dom->createElementNS('http://somenamespace', 'ttauth:Accessuser','aassdd');
    $accesscode = $dom->createElementNS('http://somenamespace', 'ttauth:Accesscode','aassdd');
    $headerNS->appendChild($accesuser);
    $headerNS->appendChild($accesscode);

    echo "<pre>";
    echo ($dom->saveXML($headerNS));
    echo "</pre>";

IT will produce the following xml as output

<?xml version="1.0" ?>
<ttauth:authHeader xmlns:ttauth="http://somenamespace">
<ttauth:Accessuser>
    ApiUserFor136
</ttauth:Accessuser>
<ttauth:Accesscode>
    test1234
</ttauth:Accesscode>
</ttauth:authHeader>

But I want the following output

<ttauth:authHeader xmlns:ttauth="http://somenamespace">

  <ttauth:Accessuser xmlns:ttauth="http://somenamespace">
    aassdd
  </ttauth:Accessuser>

  <ttauth:Accesscode xmlns:ttauth="somenamespace">
    aassdd
  </ttauth:Accesscode>

</ttauth:authHeader>

See the xmlns is not included in elements other than root element but I want xmlns to be included in all elements Is there anything I am doing wrong ??

2 Answers 2

1

Probably the PHP parser does not add renaming of the same namespace "http://somenamespace" with the same prefix "ttauth" because it is redundant. Both xmls you shown ( the output and expected ) are equivalent. If you want to be sure you have the namespaces attributes as you want, you should add them manually by using addAtribute - http://www.php.net/manual/en/domdocument.createattribute.php. See the following code snippet:

$domAttribute = $domDocument->createAttribute('xmlns:ttauth');
$domAttribute->value = 'http://somenamespace';
$accessuser->appendChild($domAttribute);

Hope it helps

Sign up to request clarification or add additional context in comments.

2 Comments

There is one problem with this too. When I append the same attribute to two child nodes it doesn't work :(
That is a correct behavior. You should create different attribute for every child node even if it has the same content.
0

instead of using

$accesuser = $dom->createElementNS('http://somenamespace', 'ttauth:Accessuser','aassdd');

I used

$accesuser = $dom->createElement('http://somenamespace', 'ttauth:Accessuser','aassdd');

and then

$accesuser->setAttribute('xmlns:ttauth', ('http://somenamespace');

it works fine for any number of nodes

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.