简体   繁体   中英

Fetching data using DOMDocument XPath Query in PHP

I am trying to fetch data using dom document xpath query and I am facing some problem while fetching it. Here is my html

<div class="abc">
<a href="xyz.php">
<span class="a1">Mexico</span>
<span class="a2">Canada</span>
<span class="a3">Brazil</span>
</a>
</div>

This is my html code. From this, I need to fetch the results in class a1 , a2 , a3 . For this I am writing like this.

$nodes = $xpath->query("//*[@class='abc']");

Can anyone help me in next step to proceed.

First, your HTML is broken. You close your <a> element twice.

Second, and with the first problem fixed, this isn't hard to do. You just need to search for span elements with the class attribute equal to one of those:

$nodes = $xpath->query("//*[@class='abc']//span[@class='a1' or @class='a2' or @class='a3']");

You could do starts-with :

$nodes = $xpath->query("//*[@class='abc']//span[starts-with(@class, 'a']");

Obviously, however, that would also match apple or antelope as well as a1 . This may not be desirable behaviour.

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