Danny_Joris
Danny_Joris

Reputation: 399

Fail to get value with xpath in php

I'm having trouble getting a value from an xml string. $query_return_string contains the following as a string:

<?xml version="1.0" encoding="UTF-8"?>
<sparql xmlns="http://www.w3.org/2001/sw/DataAccess/rf1/result">
  <head>
    <variable name="label"/>
  </head>
  <results>
    <result>
      <label>Demo sports 3</label>
    </result>
  </results>
</sparql>

This is the php code:

<?php
if ($query_return_string) {
  $query_return_dom = DOMDocument::loadXML($query_return_string);

  $xpath_dom = new DOMXPath($query_return_dom);

  $xpath = '//label';

  $entries = $xpath_dom->query($xpath);
  dsm($entries->length);
  // /sparql/results/result/label
}
?>

I'm not even bothering trying to go over the object to get the value because $entries->length returns 0. What could I be doing wrong? This seems pretty basic.

Upvotes: 1

Views: 136

Answers (1)

hcayless
hcayless

Reputation: 1046

You need to register the namespace.

$xpath_dom->registerNamespace('sw', 'http://www.w3.org/2001/sw/DataAccess/rf1/result');
$xpath = '//sw:label';

etc.

Upvotes: 3

Related Questions