PHP curl_multi_exec输出到数组

时间:2014-06-20 09:29:56

标签: php curl paypal

我正在使用PayPal的经典API,而且我在使用PHP中的curl_multi获取结果时遇到了困难。我到目前为止的代码是:

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

这已成功执行,通过注释掉CURLOPT_RETURNTRANSFER行进行验证。我能解决的是如何将返回的数据放入每个记录的数组中。我试过了:

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

这会返回一大堆0和1,但不是我需要的细节。

有人可以帮忙吗?我的大脑即将爆炸......

1 个答案:

答案 0 :(得分:3)

通过将${'ch_'.$i}更改为数组$ch[$i]然后使用curl_multi_getcontent循环遍历数组来解决此问题,如下所示:

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

这样我就可以获得数组$arr中的数据。例如,$arr['EMAIL'];

请参阅:Curl Multi and Return Transferunderstanding php curl_multi_exec