DOMDocument xmlns attributes - how to get them?
I'm using DOMDocument to read an XML (SVG), which has namespac开发者_StackOverflowes in it. I iterate through the attributes of all nodes, but I can't seem to get the 'xmlns' type attributes of the root element.
The XML looks like this :
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
id="svg2"
sodipodi:version="0.32"
inkscape:version="0.48.1 "
viewBox="0,0 534,616"
...
>
When I try something lke this :
$node= DOMDocument->documentElement;
foreach($node->attributes as $attribute) {
echo $attribute->nodeName."\n";
}
I do get the 'other' attributes like id, viewBox, etc. but not the xlmns:dc, etc.
Is there a way to get those too ?
Try with namespaceURI
The namespace URI of this node, or NULL if it is unspecified.
To get the default namespaceURI of the root node, you use
$dom->documentElement->namespaceURI;
demo
See my answer in the linked duplicate on how to get all the namespace attributes.
An alternative to that would be using XPath:
$xpath = new DOMXPath($dom);
foreach ($xpath->query('namespace::*', $context) as $node) {
echo $node->nodeValue;
}
demo
If you are parsing through the document, extracting the namespace prefixes from each attribute value and then using DOMNode::lookupNamespaceURI
( string $prefix ) to build the prefix-uri mappings will result in less overhead than using simplexml.
精彩评论