【发布时间】:2010-12-23 22:50:03
【问题描述】:
我有一个 while 循环,里面有 cUrl。 (由于各种原因,我不能使用 curl_multi。)问题是 cUrl 似乎在每次循环遍历后保存了它发布的数据。例如,如果参数 X 是第一次循环通过的 One,如果是第二次循环通过的参数 X,则 cUrl 发布:“One,Two”。它应该只发布“Two”。(尽管关闭和取消设置 curl 句柄。)
这是代码的简化版本(去掉了不必要的信息):
<?php
while(true){
// code to form the $url. this code is local to the loop.
// so the variables should be "erased" and made new for each
// loop through.
$ch = curl_init();
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
curl_setopt($ch,CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
curl_close($ch);
unset($ch);
$dom = new DOMDocument();
@$dom->loadHTML($html);
$xpath = new DOMXPath($dom);
$resultTable = $xpath->evaluate("/html/body//table");
// $resultTable is 20 the first time through the loop,
// and 0 everytime thereafter because the POSTing doesn't work right
//with the "saved" parameters.
我在这里做错了什么?
编辑
迈克尔是对的。我需要取消设置 $fields/$fields_string。新数据连接到旧数据上。
不过,我不明白为什么会发生这种情况。 $fields 是循环中的局部变量。 不应该在循环结束后将其从堆栈中删除,然后再创建一个新的吗?
【问题讨论】:
-
我想看看创建 $url、$fields 和 $fields_string 的代码。
-
最好在使用变量之前显式声明它们,即使 PHP 不要求您这样做。例如将
$fields = null;放在适当范围的开头。 -
循环没有自己的本地堆栈。如果你有一个像 for($i=0; $i
-
php 不使用块作用域