我想从选择器获取值和属性,然后根据查询获取其子项的属性和值.
请允许我举个例子.
这是结构
<div class='message'>
<div>
<a href='http://www.whatever.com'>Text</a>
</div>
<div>
<img src='image_link.jpg' />
</div>
</div>
<div class='message'>
<div>
<a href='http://www.whatever2.com'>Text2</a>
</div>
<div>
<img src='image_link2.jpg' />
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
所以我想进行一次查询以匹配所有这些.
像这样的东西:
//$dom is the DomDocument() set up after loaded HTML with $dom->loadHTML($html);
$dom_xpath = new DOMXpath($dom);
$elements = $dom_xpath->query('//div[@class="message"], //div[@class="message"] //a, //div[@class="message"] //img');
foreach($elements as $ele){
echo $ele[0]->getAttribute('class'); //it should return 'message'
echo $ele[1]->getAttribute('href'); //it should return 'http://www.whatever.com' in the 1st loop, and 'http://www.whatever2.com' in the second loop
echo $ele[2]->getAttribute('src'); //it should return image_link.jpg in the 1st loop and 'image_link2.jpg' in the second loop
}
Run Code Online (Sandbox Code Playgroud)
有没有像我在示例中那样使用多个xpath选择器的方法呢?避免一直查询并节省一些CPU.
|在单个表达式中使用union运算符(),如下所示:
//div[@class="message"]|//div[@class="message"]//a|//div[@class="message"]//img
Run Code Online (Sandbox Code Playgroud)
请注意,这将返回展平的结果集(可以这么说).换句话说,您不会像示例节目那样以三个为一组访问元素.相反,您只需迭代表达式匹配的所有内容(按文档顺序).因此,简单地迭代返回的节点//div[@class="message"]并使用DOM方法访问其子节点(对于其他元素)可能更为智能.