简体   繁体   English

DOMXpath query()不提供预期的上下文获取

[英]DOMXpath query() doesn't provide expected contextual fetching

Help greatly appreciated. 帮助极大的赞赏。

Can't make DOMXpath pull necessary DOMNodes in context. 无法使DOMXpath在上下文中提取必要的DOMNodes。
Somehow at each for iteration $a is a DOMNodeList (length=31) of what seems to be all <a> from the whole DOM instead of expected children of only one $childNode from all (and length should be 4). 不知怎的,在每次for迭代$a是什么似乎是全部的DOMNodeList(长度= 31) <a>从整个DOM, 而不是 只有一个孩子预计$childNode所有(和长度应为4)。

IMHO: To me it feels like context remains at the root of html rather than changing accordingly to foreach ... If so, is it possible to alter its behavior as reqiured? 恕我直言:对我来说,感觉上下文仍然是html的根源,而不是相应地更改为foreach ...如果是这样,是否有可能改变其行为?

PS Vuola! PS Vuola! , have tried changed Xpath query $a = $xpath->query('.') and recieved DOMElement->tagName="html" . ,尝试更改Xpath查询$a = $xpath->query('.')并收到DOMElement->tagName="html"
So, in addition to my previous question on DOMXpath DOMNodeList it seems that DOMDocument doesn't give a hell about DOMXpath. 因此,除了我先前关于DOMXpath DOMNodeList的问题外 ,似乎DOMDocument并没有给DOMXpath带来麻烦。 No connection between theese two, no context usage available... 这两个之间没有联系,没有可用的上下文...

Answer: Meh, it's just me being blind idiot..have missed 2nd parameter of DOMXpath::query() 答:嗯,只是我是个白痴。。已经错过了DOMXpath :: query()的第二个参数

$dom = new DOMDocument();
$dom -> loadHTML('HTML data');
$xpath = new DOMXpath($dom);

$myDivs = $xpath -> query('//div[@price]');

for($i=0; $i <= $myDivs->length-1; $i++) {

  $childNodes = $myDivs->item($i)->childNodes;

  foreach($childNodes as $childNode){
    $a=$xpath->query('.//a[@data-image-src]');

     if($a){
       usleep(1);
     }

 }                

You need to provide the context node as a second argument to the DOMXPath::query() method. 您需要提供上下文节点作为DOMXPath::query()方法的第二个参数。

In your particular case, that would be: 在您的特定情况下,将是:

$a = $xpath->query('.//a[@data-image-src]', $childNode);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM