I have recently come across XMLWriter. While going through the documentation I looked at
->startElementNS('prefix', 'elementName', null);
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();
<?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.