本文介绍了DOMXpath-获取元素的href属性和文本值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以我有一个像这样的HTML字符串:
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>
使用XPath,我可以使用以下Xpath查询来获取href属性的值:
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?).
推荐答案
获取
//td[@class='name']/a
,然后使用nodeValue
提取文本,并使用getAttribute('href')
提取属性.
and then pluck the text with nodeValue
and the attribute with getAttribute('href')
.
除此之外,您还可以将Xpath查询与联合运算符|
结合使用,从而可以使用
Apart from that, you can combine Xpath queries with the Union Operator |
so you can use
//td[@class='name']/a/@href|//td[@class='name']
也是.
这篇关于DOMXpath-获取元素的href属性和文本值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!