0

I'm creating XML response for the one of our clients with the namespace URLs in that using PHP. I'm expecting the output as follows,

<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema">
   <Content>
      <field1>fieldvalue1</field1>
   </Content>
</ns3:userResponse>

But by using the following code,

<?php
// create a new XML document
$doc = new DomDocument('1.0', 'UTF-8');

// create root node
$root = $doc->createElementNS('http://www.w3.org/2001/XMLSchema-instance', 'ns3:userResponse');
$root = $doc->appendChild($root);

$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');

// add node for each row
$occ = $doc->createElement('Content');
$occ = $root->appendChild($occ);


$child = $doc->createElement("field1");
$child = $occ->appendChild($child);

$value = $doc->createTextNode('fieldvalue1');
$value = $child->appendChild($value);


// get completed xml document
$xml_string = $doc->saveXML();

echo $xml_string;

DEMO: The demo is here, http://codepad.org/11W9dLU9

Here the problem is, the third attribute is mandatory attribute for the setAttributeNS PHP function. So, i'm getting the output as,

<?xml version="1.0" encoding="UTF-8"?>
<ns3:userResponse xmlns:ns3="http://www.w3.org/2001/XMLSchema-instance" xmlns:ns2="http://www.w3.org/2001/XMLSchema" ns3:schemaLocation="" ns2:schemaLocation="">
   <Content>
      <field1>fieldvalue1</field1>
   </Content>
</ns3:userResponse>

So, is there anyway to remove that ns3:schemaLocation and ns2:schemaLocation which is coming with empty value? I googled a lot but couldn't able to find any useful answers.

Any idea on this would be so great. Please help.

Stranger
  • 10,332
  • 18
  • 78
  • 115
  • possible duplicate of [How to set namespace (xmlns) declaration at root tag, with "pure DOM"?](http://stackoverflow.com/questions/26594261/how-to-set-namespace-xmlns-declaration-at-root-tag-with-pure-dom) – ThW Nov 04 '14 at 12:05
  • 1
    The namespace of an xmlns:* attribute is not its value: http://stackoverflow.com/a/26594433/2265374 – ThW Nov 04 '14 at 12:06

1 Answers1

-1

You create this attributes:

$root->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'ns1:schemaLocation','');
$root->setAttributeNS('http://www.w3.org/2001/XMLSchema', 'ns2:schemaLocation','');

remove this lines and they will be removed.

If you want to add some xmlns without using it in code is:

$attr_ns = $doc->createAttributeNS( 'http://www.w3.org/2001/XMLSchema', 'ns2:attr' );

Read this comment: http://php.net/manual/pl/domdocument.createattributens.php#98210

Styx
  • 1,303
  • 1
  • 19
  • 30