Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/254.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 选择xpath查询的第n个元素_Php_Xpath_Random - Fatal编程技术网

Php 选择xpath查询的第n个元素

Php 选择xpath查询的第n个元素,php,xpath,random,Php,Xpath,Random,我使用以下php代码从xpath查询中获取任意数量的URL: @$dom = new DOMDocument(); @$dom->loadHTML( $rawPage ); @$xpath = new DOMXPath( $dom ); @$itemCells = $xpath->query( "//td[@width=120]/a" ); 我需要从该池中随机选择一个url,以便通过cURL访问它 我想做的是获得找到的URL数量的计数,这样我就可以使用它作为rand(0,$item

我使用以下php代码从xpath查询中获取任意数量的URL:

@$dom = new DOMDocument();
@$dom->loadHTML( $rawPage );
@$xpath = new DOMXPath( $dom );
@$itemCells = $xpath->query( "//td[@width=120]/a" );
我需要从该池中随机选择一个url,以便通过cURL访问它

我想做的是获得找到的URL数量的计数,这样我就可以使用它作为
rand(0,$itemCells->length)

但是,它告诉我,
$itemCell
不能将DOMNodeList类型的对象用作数组,并且我的rand()rand()希望参数2很长,对象给定


也许有更好的方法来解决这个问题。

我怀疑由于
$length
是一个
只读属性,所以将其传递给函数时会遇到麻烦。因此,解决方案是先将a中的
$length
值保存到局部变量,然后调用,如下所示:

$max = $itemCells->length; 
$rand = rand( 0, $max);
然后,您应该能够从列表中抓取一个随机节点:

$random_node = $itemCells->item( $rand);
从那里,要获取URL,您可以执行以下操作:

$url = $random_node->attributes->getNamedItem("href")->nodeValue;

您是否尝试先将
->length
中的值保存到局部变量中<代码>$max=$itemCells->length$兰德=兰德(0,$max)。然后您应该能够执行
$random\u node=$itemCells->item($rand)
。谢谢@nickb,这似乎解决了random()问题。但是,$itemCell问题仍然存在。
$itemCell
有什么问题?谢谢,现在我如何将url检索部分添加到$itemCell->item($rand);我已经更新了我的答案。如果对您不起作用,请告诉我。太棒了!->如果要更新答案,nodeValue是正确的方法。:)我相信
$node->getAttribute('href')
$node->attributes->getNamedItem('href')->nodeValue(/code>)具有相同的效果(请参阅)。@Phoenix-好的一点-如果DOMNodeList包含doElement对象,它将起到同样的作用。我不确定是哪种情况,所以我选择了DOMNode,它保证会工作。