我正在使用simplexml通过while循环从其他提供程序加载数据。为了避免被防火墙阻挡或充斥他们的服务器,我想在500次请求后通过睡眠添加一个小延迟。这是我现有的代码......
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
// Load the XML
$url = "http://www.domain.com/models.asp?txtYear=" . $line_of_text[0] . "&txtMake=" . $line_of_text[1];
$xmlinfo = simplexml_load_file($url);
$i = 0;
$value = (string) $xmlinfo->table[$i]->txtmodel;
while ($value != '') {
$value = (string) $xmlinfo->table[$i]->txtmodel;
if ($value != '') {
fputcsv($handle, array(
$line_of_text[0],
$line_of_text[1],
$value
));
} else {
// Do nothing
}
$i++;
}
}
我希望这很容易做到 - 我期待着帮助! : - )
答案 0 :(得分:0)
计算循环的每个实例,如果它达到500,则将其置于休眠状态并重新启动它:
$meter = 0;
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 1024);
// Load the XML
$url = "http://www.domain.com/models.asp?txtYear=" . $line_of_text[0] . "&txtMake=" . $line_of_text[1];
$xmlinfo = simplexml_load_file($url);
$i = 0;
$value = (string) $xmlinfo->table[$i]->txtmodel;
while ($value != '') {
$value = (string) $xmlinfo->table[$i]->txtmodel;
if ($value != '') {
fputcsv($handle, array(
$line_of_text[0],
$line_of_text[1],
$value
));
} else {
// Do nothing
}
$i++;
}
//Increase the meter by 1
$meter++;
//Check if the limit is reached and if yes, sleep for 60 seconds
if($meter == 500){
sleep(60);
$meter = 0;
}
}