PHP中的cURL While循环只运行一次

时间:2012-02-29 11:28:45

标签: php curl while-loop

while($dataR = mysql_fetch_array($data)){
    $postcode = str_replace(" ", "+", $dataR['Postcode']);
    echo $postcode."<br />";
    $oPostcode = $dataR['Postcode'];
    // Retrieve the DOM from a given URL
    $url = 'http://www.1.com';
    $fields = array(
                'txtPostCode'=>urlencode($oPostcode)


            );

    //url-ify the data for the POST
    foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
    rtrim($fields_string,'&');

    $ch = curl_init();

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_POST,count($fields));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

    //execute post
    $result = curl_exec($ch);
    curl_close($ch);
    unset($ch);
    //close connection

    $html = str_get_html($result);
    print_r($html);
}

这就是我的代码。但是cURL部分只在第一次运行 - 我该怎么办?我试图理解curl_multi_exec,但找不到简单的答案。

2 个答案:

答案 0 :(得分:1)

最好将cURL请求与循环分开... 所以像这样的东西会...... ..

while($dataR = mysql_fetch_array($data)){
$postcode = str_replace(" ", "+", $dataR['Postcode']);
echo $postcode."<br />";
$oPostcode = $dataR['Postcode'];
// Retrieve the DOM from a given URL
$url = 'http://www.1.com';
$fields = array(
            'txtPostCode'=>urlencode($oPostcode)


        );

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');


// Execute youru cURL here.
$data = array(
'url' => $url,
'fiels' => count($fields),
'field_string' => $fields_string
);
executecURL($data);

$html = str_get_html($result);
print_r($html);
}

function executecURL($data) {
    $ch = curl_init();
    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_URL,$data['url']);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_POST,count($data['fields']));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data['fields_string']);

    //execute post
    $result = curl_exec($ch);
    curl_close($ch);
    unset($ch);
    //close connection
}

答案 1 :(得分:0)

尝试取消设置' $ field &amp;的 $ field_string


unset($fields);
unset($fields_string);

重新使用之前