Is registerNamespace required in PHP DOMXPath?

I work with XML as follows: (this is the standard container.xml in the epub book)

<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
   <rootfiles>
      <rootfile full-path="OEBPS/9780765348210.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>

I am trying to parse it using PHP. This is my code:

$c = new DOMDocument();
$c->load($filename);
$x = new DOMXPath($c);
//fine up to here!

//is this even what I'm supposed to be doing?
$x->registerNamespace('epub', 'urn:oasis:names:tc:opendocument:xmlns:container');
$root = $x->query('/epub:container/epub:rootfiles/epub:rootfile');

//fine down from here!
$opf = $root->item(0)->getAttribute('full-path'); //I know I should check if the element there and if it has the attribute. Not important.

My question is: Is there a way not to make this call registerNamespace? I'm not sure that different epubs set this value a little differently, and I need this code to work any epub I throw at it.

+5
source share
2 answers

AFAIK: no. XML documents can suffer from name conflicts, so namespaces are used. You cannot use XPath on XML documents without registering one or more namespaces or setting prefixes for them.

XML (xmlns="<namespace identifier>"), . , , , , , - : :

// ... load the DOMDocument ...

$defaultNamespace = $c->lookupNamespaceURI($c->namespaceURI);
$x->registerNamespace('epub', $defaultNamespace);

// ... now query like in your example
$root = $x->query('/epub:container/epub:rootfiles/epub:rootfile');
+2

Max, DOMXPath, XML- . , - . , , , , XML . XML- , registerNamespace, "epub" .

<?xml version="1.0"?>
<container version="1.0">
   <rootfiles>
      <rootfile full-path="OEBPS/9780765348210.opf" media-type="application/oebps-package+xml"/>
   </rootfiles>
</container>

XML, , .

0

All Articles