Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
652 views
in Technique[技术] by (71.8m points)

php - DOMXpath - Get href attribute and text value of an a element

So I have a HTML string like this:

<td class="name">
   <a href="/blah/somename23123">Some Name</a>
</td>
<td class="name">
   <a href="/blah/somename28787">Some Name2</a>
</td>

Using XPath I'm able to get value of href attribute using this Xpath query:

 $domXpath = new DOMXPath($this->domPage);
 $hrefs = $domXpath->query("//td[@class='name']/a/@href");
 foreach($hrefs as $href) {...}

And It's even easier to get a text value, like this:

 // Xpath auto. strips any html tags so we are 
 // left with clean text value of a element
 $domXpath = new DOMXPath($this->domPage);
 $names = $domXpath->query("//td[@class='name']/");
 foreach($names as $name) {...}

Now I'm curious to know, how can I combine those two queries to get both values with only one query (If it's something like that even posible?).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Fetch

//td[@class='name']/a

and then pluck the text with nodeValue and the attribute with getAttribute('href').

Apart from that, you can combine Xpath queries with the Union Operator | so you can use

//td[@class='name']/a/@href|//td[@class='name']

as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...