4

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.

2

2 Answers 2

2

DOMDocument constructor does not take the contents, but version and encoding. Instead of:

$path = "index.xml";
$content = file_get_contents($path);
$dom = new DOMDocument($content);

Try this:

$path = "index.xml";
$doc = new DOMDocument();
$doc->load($path);
Sign up to request clarification or add additional context in comments.

Comments

0

You must define namespace in your xml file:

<?xml version="1.0"?>
<root xmlns:sf="http://developer.apple.com/namespaces/sf">
    <sf:page>
         <sf:section>
              <sf:layout>
                  <sf:p>My Content</sf:p>
              </sf:layout>
         </sf:section>
    </sf:page>
</root>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.