Search for all elements with given tag name in specified namespace in PHP

Description

The following code shows how to search for all elements with given tag name in specified namespace.

Example


/*  www  . j av a 2  s. c  om*/
<?php

$xml = <<<EOD
<?xml version="1.0" ?>
<chapter xmlns:xi="http://www.w3.org/2001/XInclude">
<title>my books</title>
<para>
 <xi:include href="test.xml">
  <xi:fallback>
   <error>xinclude:test.xml not found</error>
  </xi:fallback>
 </xi:include>
 <include>
  This is another namespace
 </include>
</para>
</chapter>
EOD;
$dom = new DOMDocument;

// load the XML string defined above
$dom->loadXML($xml);

foreach ($dom->getElementsByTagNameNS('http://www.w3.org/2001/XInclude', '*') as $element) {
    echo 'local name: ', $element->localName, ', prefix: ', $element->prefix, "\n";
}
?>

The following code is for test.xml.


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE books [/*from  ww w .  j  a v a  2  s.com*/
  <!ELEMENT books   (book+)>
  <!ELEMENT book    (title, author+, xhtml:blurb?)>
  <!ELEMENT title   (#PCDATA)>
  <!ELEMENT blurb   (#PCDATA)>
  <!ELEMENT author  (#PCDATA)>
  <!ATTLIST books   xmlns        CDATA  #IMPLIED>
  <!ATTLIST books   xmlns:xhtml  CDATA  #IMPLIED>
  <!ATTLIST book    id           ID     #IMPLIED>
  <!ATTLIST author  email        CDATA  #IMPLIED>
]>
<?xml-stylesheet type="text/xsl" href="style.xsl"?>
<books xmlns="http://java2s.com/" xmlns:xhtml="http://www.w3.org/1999/xhtml">
  <book id="php-basics">
    <title>PHP Basics</title>
    <author email="t@no.com">Tom</author>
    <author email="j@no.com">Jack</author>
    <xhtml:blurb>PHP Basics</xhtml:blurb>
  </book>
  <book id="php-advanced">
    <title>PHP Programming</title>
    <author email="j@no.php">Jack</author>
  </book>
</books>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser