【问题标题】:Recursive in a while loop in PHPPHP中的while循环中的递归
【发布时间】:2013-05-26 08:18:11
【问题描述】:

我有一个来自数据库的客户端列表,对于每个客户端,我需要使用 curl 使用我列表中的随机代理 IP 从网站获取他们的数据。递归函数尝试使用 ip 获取 html,如果 ip 不起作用/太慢,我想跳过 ip 并获取另一个随机 ip,直到我从网站获取客户端数据,然后继续下一步客户端等等。

目前的问题是,如果一个 ip 不起作用,递归函数似乎会跳过客户端记录并迭代到下一个客户端记录而不递归。将不胜感激任何可以在这里阐明的人。提前致谢。

$sql = mysql_query( 'SELECT * FROM client' );

while( $row = mysql_fetch_array( $sql ) ) {
    $fields = array( 'clientID' => $row['clientID'] );

    $fields_string = '';
    foreach($fields as $key=>$value) { $fields_string .= urlencode($key).'='.urlencode($value).'&'; }
    rtrim($fields_string,'&');

    $result = getHTML( $row['url'], $fields_string ); //  call to recursive function
    var_dump($result);
}

$proxy = json_decode(file_get_contents('array2.json'), true);

function getHTML( $url, $fields_string ) {
    global $proxy;

    $randKey = array_rand( $proxy );
    $ip = $proxy[$randKey];

    $ch = curl_init( );
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_PROXY, $ip );
    curl_setopt($ch, CURLOPT_POST, true );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $result = curl_exec($ch);
    curl_close($ch);

    if( !$result || !stristr( $result, '<span class="title">' ) ) {
        flush( );
        ob_flush( );
        echo $ip . '<br>'; // just for debugging
        getHTML( $url, $fields_string ); // recursion happen here
    }
    else {
        return $result;
    }
}

【问题讨论】:

  • 因为getHTML返回一个值,你应该return getHTML(...)以便终端结果到达原始调用者。
  • 我认为问题可能出在 if 语句中,请尝试 if (!result &amp;&amp; !stristr(..))if ( !($result &amp;&amp; stristr(..)))
  • 哦,非常感谢保罗。我不知道我需要返回 getHtml 调用。您可以发布答案以便我给您投票吗?再次感谢!

标签: php curl recursion proxy


【解决方案1】:

由于 getHTML 返回一个值,您应该return getHTML(...) 以便终端结果到达原始调用者。

【讨论】:

    猜你喜欢
    • 2013-09-30
    • 2020-06-28
    • 1970-01-01
    • 2013-08-12
    • 2016-03-19
    • 2016-02-27
    • 2012-08-04
    • 2013-12-26
    • 2016-11-27
    相关资源
    最近更新 更多