简体   繁体   中英

Using Xpath to get Data from XML with Namespace

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.

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM