PHP DOMDocument:如何选择特定标记下的所有链接 [英] PHP DOMDocument : how to select all links under a specific tag
问题描述
我刚开始使用php DOMDocument,但遇到了一些麻烦。
我将如何选择特定节点下的所有链接节点
I'm just getting started with using php DOMDocument and am having a little trouble. How would I select all link nodes under a specific node lets say
在jquery中我可以简单地执行。.$('h5> a')
,这将为我提供h5下的所有链接。
in jquery i could simply do.. $('h5 > a') and this would give me all the links under h5.
我将如何使用DOMDocument方法在php中做到这一点?
我尝试使用 phpquery ,但由于某种原因,它无法读取html页面我正在尝试解析。
how would i do this in php using DOMDocument methods? I tried using phpquery but for some reason it can't read the html page i'm trying to parse.
推荐答案
据我所知,jQuery将选择器查询重写为XPath。
As far as I know, jQuery rewrites the selector queries to XPath. Any node jQuery can select, XPath also can.
h5> a
表示选择任何直接父节点为 h5
的 a
节点。可以轻松地将其转换为XPath查询: // h5 / a
。
h5 > a
means select any a
node for which the direct parent node is h5
. This can easily be translated to a XPath query: //h5/a
.
因此,使用DOMDocument:
So, using DOMDocument:
$dom = new DOMDocument;
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$nodes = $xpath->query('//h5/a');
foreach ($nodes as $node) {
// do stuff
}
这篇关于PHP DOMDocument:如何选择特定标记下的所有链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!