PHP SimpleXML-> addChild - unwanted empty namespace attribute

I am trying to use the SimpleXML addChild method for SimpleXMLElement (actually SimpleXMLIterator, which is a subclass of SimpleXMLElement), to add children.

My problem is that the source document contains a mixture of elements with and without namespaces. Here is a simple example (no pun intended):

<?xml version="1.0" encoding="UTF-8"?>
  <ns1:a xmlns:ns1="http://www.abc.com">
</ns1:a>

PHP code:

$it = new SimpleXMLIterator ('./test.xml', 0, true);
$it->addChild('d', 'another!'); // adds new child element to parent NS
$it->addChild('c', 'no namespace for me!', ''); // puts xmlns="" every time :(

//output xml in response:
header('Content-Type: text/xml');

echo $it->saveXML();

The problem - as the comment says - is that if I want to place a child element without a namespace inside the parent element with a namespace, I get an empty XML namespace attribute every time (output above PHP code):

<?xml version="1.0" encoding="UTF-8"?>
  <ns1:a xmlns:ns1="http://www.abc.com">
  <ns1:d>another!</ns1:d>
  <c xmlns="">no namespace for me!</c>
</ns1:a>

-, XML (, Xerces), , , , , .

- ?

:}

+3
1

SimpleXML c . , xmlns, . c, node. - ns1. ( d.)

xmlns, , xmlns="http://example.com" . $it->addChild('c', 'no ns', 'http://example.com') <c>no ns</c>.

, . addAttribute. SimpleXML. , xmlns .

+5

Source: https://habr.com/ru/post/1785023/


All Articles