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.

4
  • once you registered the prefix, you can query nodes with that prefix, e.g. w:foo/w:bar with the xpath() method. Please clarify the problem. Commented Jun 13, 2011 at 9: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... Commented Jun 13, 2011 at 9:28
  • in that case, you have to use children(). See PHP SimpleXML Namespace Problem for a similar question. Commented Jun 13, 2011 at 9:30
  • @Gordon - excellent thank you. I've now used $price = $entry->children('w', true)->price; and that has done the trick! Commented Jun 13, 2011 at 10:03

1 Answer 1

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')
Sign up to request clarification or add additional context in comments.

1 Comment

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?

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.