PHP: get all declared DOMElement namespaces

I am using the DOM extension to parse an XML file containing xml namespaces . I would think that namespace declarations are treated like any other attribute, but my tests do not seem to be consistent. I have a document that starts as follows:

<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:prism="http://purl.org/rss/1.0/modules/prism/"
    xmlns:admin="http://webns.net/mvcb/"
    >

And the test code:

$doc = new DOMDocument();
$doc->loadXml(file_get_contents('/home/soulmerge/tmp/rss1.0/recent.xml'));
$root = $doc->documentElement;
var_dump($root->tagName);
# prints 'string(7) "rdf:RDF"'
var_dump($root->attributes->item(0));
# prints 'NULL'
var_dump($root->getAttributeNode('xmlns'));
# prints 'object(DOMNameSpaceNode)#3 (0) {}'

So the questions are:

  • Does anyone know where I can find the documentation DOMNameSpaceNode? A search on php.net does not yield any useful result.
  • How to extract all these namespace declarations from this DOMElement?
+5
source share
2 answers

, XPath .
.

<?php
$doc = new DOMDocument;
$doc->loadxml('<rdf:RDF
    xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
    xmlns="http://purl.org/rss/1.0/"
    xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/"
    xmlns:dc="http://purl.org/dc/elements/1.1/"
    xmlns:syn="http://purl.org/rss/1.0/modules/syndication/"
    xmlns:prism="http://purl.org/rss/1.0/modules/prism/"
    xmlns:admin="http://webns.net/mvcb/"
    >
...
</rdf:RDF>');
$context = $doc->documentElement;

$xpath = new DOMXPath($doc);
foreach( $xpath->query('namespace::*', $context) as $node ) {
  echo $node->nodeValue, "\n";
}

http://www.w3.org/XML/1998/namespace
http://webns.net/mvcb/
http://purl.org/rss/1.0/modules/prism/
http://purl.org/rss/1.0/modules/syndication/
http://purl.org/dc/elements/1.1/
http://purl.org/rss/1.0/modules/taxonomy/
http://purl.org/rss/1.0/
http://www.w3.org/1999/02/22-rdf-syntax-ns#

edit btw: DOMNameSpaceNode. "" () ext/dom/php_dom.c
,

"nodeName", "nodeValue", "nodeType",
"prefix", "localName", "namespaceURI",
"ownerDocument", "parentNode"

, DOMNode.

+9

,

echo $root->getAttributeNode('xmlns')->nodeValue . "\n";
echo $root->getAttribute('xmlns') . "\n";
echo $root->getAttribute('xmlns:syn') . "\n";

,

http://purl.org/rss/1.0/
http://purl.org/rss/1.0/
http://purl.org/rss/1.0/modules/syndication/

DOMNameSpaceNode - Node, NodeCollection.

, , - PHP DOM , XPath ( VolkerK) - , .

+2

All Articles