I am creating an Atom feed, when I tried below to add xmlns:i
as an attribute -
$node->addAttribute("xmlns:i","http://www.w3.org/2001/XMLSchema-instance");
I got this as an output -
i="http://www.w3.org/2001/XMLSchema-instance"
"xmlns:"
part was cut off. do I need to escape the :
-character? Or is they any other way to add this namespace?
If you don’t want to have to add a dummy attribute to your root element, you can declare the namespace manually on it by adding an
xmlns
attribute for youri
prefix:In order to do so, and as hinted in an existing answer (Unable to add Attribute with Namespace Prefix using PHP Simplexml), you have to prefix the new attribute with
xmlns:
(since thexmlns:
namespace prefic is not declared in your document). And sincexmlns:
is part of the name of that attribute, you therfore need two occurrences ofxmlns:
Gives (formatted manually for readability):
So this
xmlns:
prefixing seems to cheat it. Note that if you reload the element after setting that attribute, it is possible to use the namespace uri as well when adding children, and this without specifying the prefix:Gives (again, formatted manually):
This second example seems to be closer to the intended (or at least expected) use.
Note that the only way to do this properly would be to use the more complete (but unfortunately also more complex and more verbose) DOMDocument classes. This is outlined in How to declare an XML namespace prefix with DOM/PHP?.
I found this looking for the same thing, and none of the answers really worked for me. So, I tried a different route. If SimpleXML isn't managing namespace correctly, use DOM instead.
So, something like this should work:
That will result in this:
If you want to add an attribute from the namespace/prefix
i
to $node don't bother declaring the namespace beforehand. Just use the third parameter of addAttribute() to provide the namespace uri for the prefix you're using in the first parameter.prints
If the attribute itself isn't needed, you can then remove it with
unset()
, leaving the namespace declaration.