【问题标题】:PHP & cUrl - POST problems in while loopPHP & cUrl - while 循环中的 POST 问题
【发布时间】: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 不使用块作用域

标签: php loops curl libcurl


【解决方案1】:

您是否尝试过打印 $fields_string 和 $fields 以在每次循环迭代时查看它们的值?也许其中一个没有得到清除。由于您每次都使用 curl_init/curl_close,因此问题可能不在 curl 本身。

【讨论】:

  • 就是这样。如果您能回答编辑问题,我将永远、不可撤销、无比感激。
  • 莎拉在上面很好地涵盖了它。这对我来说也很令人沮丧 - 来自 C 背景,在循环中没有明确定义的范围很烦人。我刚刚学会了总是在循环中初始化局部变量。 PHP 确实具有良好范围的一个地方是函数——这也许是你应该放置 curl 代码的地方,在一个很好的“getSiteData($url,$fields)”函数中更干净,它会复制 $fields 和 $url进入本地范围。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-06
  • 2014-02-02
  • 1970-01-01
  • 2011-06-19
  • 1970-01-01
  • 2011-06-17
  • 2012-10-29
相关资源
最近更新 更多