rickyduck
rickyduck

Reputation: 4084

cURL in PHP While Loop only runs once

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);
}

Thats my code. However the cURL section only runs on the first time - what must I do? I have tried to understand the curl_multi_exec but can't find a simple answer.

Upvotes: 0

Views: 4678

Answers (2)

Robert Wilson
Robert Wilson

Reputation: 669

It would be best to separate your cURL request from the loop... so something like this would do..

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
}

Upvotes: 1

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Try unset'ting the $field & $field_string


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

before re-using it

Upvotes: 0

Related Questions