How do you query namespaces with PHP/XPath/DOM

Posted by Alsbury on Stack Overflow See other posts from Stack Overflow or by Alsbury
Published on 2010-05-04T12:10:27Z Indexed on 2010/05/25 12:51 UTC
Read the original article Hit count: 350

Filed under:
|
|
|
|

I am trying to query an XML document that uses namespaces. I have had success with xpath without namespaces, but no results with namespaces. This is a basic example of what I was trying. I have condensed it slightly, so there may be small issues in my sample that may detract from my actual problem.

Sample XML:

<?xml version="1.0"?>
<sf:page>
     <sf:section>
          <sf:layout>
              <sf:p>My Content</sf:p>
          </sf:layout>
     </sf:section>
</sf:page>

Sample PHP Code:

<?php
$path = "index.xml";

$content = file_get_contents($path);

$dom = new DOMDocument($content);

$xpath = new DOMXPath($dom);
$xpath->registerNamespace('sf', "http://developer.apple.com/namespaces/sf");

$p = $xpath->query("//sf:p", $dom);

My result is that "p" is a "DOMNodeList Object ( )" and it's length is 0. Any help would be appreciated.

© Stack Overflow or respective owner

Related posts about php

Related posts about Xml