Darwin Darwin - 1 month ago 15
PHP Question

XMLWriter in PHP, using a namespace in startElement rather then startElementNS

I have recently come across XMLWriter. While going through the documentation I looked at

startElement
and
startElementNS
.

->startElement('prefix:elementName');
(colon in the string)

->startElementNS('prefix', 'elementName', null);


I have incorporated both into my XML and received the following
<prefix:elementName


My overall XML does not have any issues, but is the end result identical or am I missing something?

If using startElementNS does not result in a different outcome, would this just fall to preference?

ThW ThW
Answer

null is not a valid type for the namespace argument of startElementNS(). It has to be a string. PHPs behavior is a little strange - it should report it as an error or cast it into an empty string. If you provide the empty string you will see the difference:

$writer = new XMLWriter;
$writer->openURI('php://output');
$writer->startDocument('1.0', 'UTF-8');
$writer->startElementNS('prefix', 'elementName', '');
$writer->endElement();
$writer->endDocument();

Output:

<?xml version="1.0" encoding="UTF-8"?>
<prefix:elementName xmlns:prefix=""/>

While the variant with startElement() results in:

<?xml version="1.0" encoding="UTF-8"?>
<prefix:elementName/>

The first version includes a namespace definition for the used prefix. The namespace aware methods will add namespace definitions as needed. The second version would be invalid XML if the XML parser is namespace aware.

If your using namespaces, use the namespace aware methods.

Originally XML did not have namespaces and the ':' was an allowed character in tag names. The definition allows for a lot of characters. So old parsers Java still have a mode that ignores namespaces and parses XML that way. Other like MySQL never implemented namespaces. PHP (libxml) on the other hand always work namespace aware. They did not change the behavior of the non namespace aware methods, so you can add nodes names with colons if you use them. It is possible to generate a valid XML string with namespaces that way (add the namespaces as attributes), just like it is possible to do the same using only string functions.

Comments