在PHP中循环时出现奇怪的API问题

时间:2012-06-18 23:28:30

标签: php mysql api curl

我正在使用此API:https://gatewaydtx1.giact.com/gVerifyV2/POST/Verify.asmx?op=Call在php中使用curl。我可以通过一次调用API来进行测试。但是当我尝试遍历几条记录时,我在第一条记录之后的每次尝试都会收到错误。

这是我的代码:

<?
//set the variables for posting
$CompanyID = "123";
$Token = "013443234-224e-4f46-bad4-6693deae2231";
$CheckNumber = "1";
$Amount = "30";
$UniqueID = "111";
$url = "https://gatewaydtx1.giact.com/gVerifyV2/POST/Verify.asmx/Call";

//Get the records from table
$sql = "SELECT id,account_no,routing_no FROM banktable WHERE(status = 'queued') LIMIT 0,100";
$result = mysql_query($sql) or die("Error: " . mysql_error() . "<br>");
while($row = mysql_fetch_array($result)) {
    $RoutingNumber = $row['routing_no'];
    $AccountNumber = $row['account_no'];    
    //Do the curl
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_VERBOSE, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_URL, $url );
    $post_array = array(
        "CompanyID"=>$CompanyID,
        "Token"=>$Token,
        "RoutingNumber"=>$RoutingNumber,
        "AccountNumber"=>$AccountNumber,
        "CheckNumber"=>$CheckNumber,
        "Amount"=>$Amount,
        "UniqueID"=>$UniqueID,
    );

    //url-ify the data
    foreach($post_array as $key=>$value){
        $post_array_string .= $key.'='.$value.'&';
    }
    $post_array_string = rtrim($post_array_string,'&');

    //set the url, number of POST vars, POST data
    curl_setopt($ch,CURLOPT_POST,count($post_array ));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$post_array_string);
    $response = curl_exec($ch);
    echo $response;
    curl_close($ch);
}
?>

以下是循环4行后此代码输出的内容:

<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.giact.com/webservices/gVerifyV2/">33302261|true|No Data|ND00</string>
Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).
Guid should contain 32 digits with 4 dashes (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).

请注意,它尝试的第一条记录产生了正确的结果。在那之后,错误。即使我在这里特别提到我的循环,我也应该注意,如果我只是在页面上硬编码两个或更多卷发,也会发生这种情况。

2 个答案:

答案 0 :(得分:0)

//url-ify the data
foreach($post_array as $key=>$value){
    $post_array_string .= $key.'='.$value.'&';
}
$post_array_string = rtrim($post_array_string,'&');

我认为你需要在每个循环中清除$ post_array_string变量。

unset($post_array_string);

答案 1 :(得分:0)

在:

foreach($post_array as $key=>$value){

添加:

$post_array_string = '';

或者您可以使用http_build_query()功能。