我想取一个变量的随机值,并将其插入cURL命令中。此外,在添加了这个随机变量的值后,cURL应该使用这个值运行函数,在函数的最后,我希望它向第一个值添加一个不同的值,这样函数就会完成,就会有结果。
$kinds = array(
"http://fruits.com/select.php?=",
"http://vegtables.com/select.php?=",
);
$random = array_rand($kinds);
function get_fruits($fruit){
//get content
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$kinds[$random].$fruit);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
$test = get_fruits('apple');
echo $test;
$测试得到一个空值。空白的正如您所看到的,它采用随机的$kinds,然后将$fruit值添加到函数之后。
我认为这是因为函数的第二行:
curl_setopt($ch,CURLOPT_URL,$kinds[$random].$fruit);
因为如果我更改
$kinds[$random].$fruit
至
'http://fruits.com/select.php?='
一切都很好。我的意思是,当我使用下一种方式时:
curl_setopt($ch,CURLOPT_URL,'http://fruits.com/select.php?='.$fruit);
一切都很完美。
但我不想定义http://frutis.com',我想从array_rand函数中给出的url中获取一个随机url。
我不知道该怎么办。
非常感谢。我已经尝试了以下方法:
curl_setopt($ch,CURLOPT_URL,"$kinds[$random]".$fruit);
curl_setopt($ch,CURLOPT_URL,$kinds[$random].$fruit);
curl_setopt($ch,CURLOPT_URL,$kinds[$random]."/select.php?=".$fruit); //(when I defined the $kinds as the url only without the select.php)
$kinds和$random变量是在get_fruits()函数外部定义的,因此在函数内部对它们使用关键字global,或者将它们发送到函数。
function get_fruits($fruit){
global $kinds, $random;
...
}
或
function get_fruits($fruit, $kinds, $random){
...
}
$test = get_fruits('apple', $kinds, $random);
此外,您可能只想向函数发送一个参数url,而不是同时发送数组和索引。