1

I've been banging my head against a brick wall with this so would really appreciate some help. I'm using xpath for the first time and have it doing most of the things I need without any problems.

Here is an example snippet:

 $urlw = "http://www.wahanda.com/rss/mobdeal.xml";
 $wf = gzopen ($urlw, 'r');
 $wxml = new SimpleXMLElement (fread ($wf, 1000000));

 foreach($wxml->xpath ('/rss/channel/item') as $entry) 
 {
    $price = $entry->price;
    echo $price . "<br/>"; 
 }

My problem is that the feed I'm currently using has namespace declarations so the "price" node is in fact "w:price". Some of the nodes I want to use are prefixed with "w:" while others aren't. My code is therefore failing to pick up the contents of the prefixed nodes. Can someone please tell me how I work around this? From reading around I've added the following:

 $wxml->registerXPathNamespace('w', 'http://www.wahanda.com/ns/1.0');

but still not sure what I need to do from here on.

Thanks a lot in advance for your help.

Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
Chris
  • 57
  • 1
  • 1
  • 7
  • once you registered the prefix, you can [query nodes with that prefix](http://stackoverflow.com/search?q=registerXPathNamespace+php), e.g. `w:foo/w:bar` with the [`xpath()` method](http://de2.php.net/manual/en/simplexmlelement.xpath.php). Please clarify the problem. – Gordon Jun 13 '11 at 09:03
  • Hi @Gordon - I'm trying to work out what I need to replace $price = $entry->price; with in my code above to give me the individual w:price values for each "item" in the XML. I used $price = $wxml->xpath ('//w:price') per the suggestion below but this returns an array - given there's only one "w:price" node in each "item" I thought it would work... – Chris Jun 13 '11 at 09:28
  • in that case, you have to use [`children()`](http://de2.php.net/manual/en/simplexmlelement.children.php). See [PHP SimpleXML Namespace Problem](http://stackoverflow.com/questions/6027398/php-simplexml-namespace-problem/6027507#6027507) for a similar question. – Gordon Jun 13 '11 at 09:30
  • @Gordon - excellent thank you. I've now used $price = $entry->children('w', true)->price; and that has done the trick! – Chris Jun 13 '11 at 10:03

1 Answers1

0

You are on the right track. All you need to do is write an xpath query with the namespace. Something like:

$wxml->xpath ('//w:price')
datasage
  • 19,153
  • 2
  • 48
  • 54
  • Thanks @datasage. When I replace $price = $entry->price; with $price = $wxml->xpath ('//w:price'); in the code above, the output I get is "Array". There is however only one "w:price" node in each "item" so I thought it should be picking out an individual price each time, not an array? – Chris Jun 13 '11 at 09:22