Search code examples
phpxmlnamespacesxmlwriter

Tracking namespace declarations with XMLWriter


I'm working on an XML webservice (in PHP!), and in order to do things 'right', I want to use XMLWriter instead of just concatinating strings and hoping for the best.

I'm using XML namespaces everywhere using ->startElementNS and ->writeElementNS. The problem, is that every time I use these functions a new namespace declaration is also writting.

While this is correct syntax, it's a bit unneeded. I'd like to make sure my namespace declaration is only written the first time it's used in the context of a document.

Is there an easy way to go about this with XMLWriter, or am I stuck subclassing this and managing this manually.

Thanks, Evert


Solution

  • You can pass NULL as the uri parameter.

    <?php
    $w = new XMLWriter;
    $w->openMemory();
    $w->setIndent(true);
    $w->startElementNS('foo', 'bar', 'http://whatever/foo');
    $w->startElementNS('foo', 'baz', null);
    $w->endElement();
    $w->endElement();
    echo $w->outputMemory();
    prints
    <foo:bar xmlns:foo="http://whatever/foo">
     <foo:baz/>
    </foo:bar>