Create a namespace context for the next XPath query in PHP

Description

The following code shows how to create a namespace context for the next XPath query.

Example


/* w w  w  .  ja v a 2s .com*/
<?php
   $xml=<<<XML
   <book xmlns:chap="http://example.org/chapter-title">
         <title>My Book</title>
         <chapter id="1">
           <chap:title>Chapter 1</chap:title>
           <para>Introduction</para>
         </chapter>
         <chapter id="2">
           <chap:title>Chapter 2</chap:title>
           <para>Examp-le</para>
         </chapter>
   </book>
XML;

    $sxe=new SimpleXMLElement($xml);
    $sxe->registerXPathNamespace('c','http://example.org/chapter-title');
    $result=$sxe->xpath('//c:title');
    foreach ($result as $title){
        echo $title . "<br>";
    }
?>

The code above generates the following result.





















Home »
  PHP Tutorial »
    XML »




DOM
SimpleXML
SimpleXMLElement
XML Parser