PHP curl_multi_exec output to array

2019-07-21 14:31发布

I'm working with PayPal's classic API, and I'm having difficulty with getting the results from curl_multi in PHP. The code I have so far is:

<?php
$mh = curl_multi_init();
include('../connect.php');

$sql = "SELECT * FROM transactions ORDER BY ID asc LIMIT 0,2";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)){
$rid = $row['ID'];
$tid = $row['transID'];

$sandbox = FALSE;

// Set PayPal API version and credentials.
$api_version = '85.0';
$api_endpoint = 'https://api-3t.paypal.com/nvp';
$api_username = 'MY_USER';
$api_password = 'MY_PASS';
$api_signature = 'API_SIGNATURE';

$request_params = array
               (
'USER' => $api_username, 
'PWD' => $api_password, 
'SIGNATURE' => $api_signature, 
'VERSION' => $api_version, 
'METHOD' => 'GetTransactionDetails',
'TRANSACTIONID' => $tid
               );

$nvp_string = '';
foreach($request_params as $var=>$val)
{
   $nvp_string .= '&'.$var.'='.urlencode($val);   
}

${'ch_' . $i} = curl_init();
      curl_setopt(${'ch_' . $i}, CURLOPT_VERBOSE, 1);
      curl_setopt(${'ch_' . $i}, CURLOPT_SSL_VERIFYPEER, FALSE);
      curl_setopt(${'ch_' . $i}, CURLOPT_TIMEOUT, 30);
      curl_setopt(${'ch_' . $i}, CURLOPT_URL, $api_endpoint);
      curl_setopt(${'ch_' . $i}, CURLOPT_RETURNTRANSFER, 1);
      curl_setopt(${'ch_' . $i}, CURLOPT_POSTFIELDS, $nvp_string);


    curl_multi_add_handle($mh, ${'ch_'.$i});
    $i++;
}
}
include('../close.php');
    $running = null;
    do {
        curl_multi_exec($mh, $running);
    } while ($running);
?>

This is successfully executing, verified by commenting out the CURLOPT_RETURNTRANSFER line. What I can't work out is how to get the returned data into an array for each record. I've tried:

$result = curl_multi_exec($mh, $running);
print_r($result);

This returns a whole bunch of 0s and 1s, but not the details I need.

Can anyone help? My brain is about to explode...

标签: php curl paypal
1条回答
Bombasti
2楼-- · 2019-07-21 15:03

Solved it by changing the ${'ch_'.$i} to an array $ch[$i] then looping through the array using curl_multi_getcontent as follows:

foreach ($ch as $a)
{
    $result = curl_multi_getcontent($a);
    parse_str($result, $arr);
    print_r($arr);
    echo "--------------------------------------------------\n";
}

This then lets me the data in the array $arr. For example, $arr['EMAIL'];

See as well: Curl Multi and Return Transfer and understanding php curl_multi_exec.

查看更多
登录 后发表回答