从curl响应字符串中获取特定变量

时间:2017-10-04 10:34:52

标签: php curl payment-gateway php-5.3 php-curl

我从curl得到响应,如下所示:

Accepted=AVSAUTH:TEST:::829649376:N::U
ENTRYMETHOD=KEYED
historyid=829649376
MERCHANTORDERNUMBER=14700000186
orderid=646526156
PAYTYPE=MasterCard
recurid=0
refcode=829649376-TEST
result=1
Status=Accepted
transid=0

我想得到各种变量,例如status = Accepted,这样我就可以将它们存储在我的数据库中。任何帮助都会非常值得赞赏。

3 个答案:

答案 0 :(得分:2)

preg_match是你的朋友:

<?
$result = "Accepted=AVSAUTH:TEST:::829649376:N::U
ENTRYMETHOD=KEYED
historyid=829649376
MERCHANTORDERNUMBER=14700000186
orderid=646526156
PAYTYPE=MasterCard
recurid=0
refcode=829649376-TEST
result=1
Status=Accepted
transid=0";

preg_match_all("/^([^=]+)=(.*)$/m", $result, $regs, PREG_SET_ORDER);

$data = [];
foreach($regs as $reg) {
    $data[$reg[1]] = $reg[2];
}

print_r($data);
?>

$ data将是一个哈希数组:

Array
(
    [Accepted] => AVSAUTH:TEST:::829649376:N::U
    [ENTRYMETHOD] => KEYED
    [historyid] => 829649376
    [MERCHANTORDERNUMBER] => 14700000186
    [orderid] => 646526156
    [PAYTYPE] => MasterCard
    [recurid] => 0
    [refcode] => 829649376-TEST
    [result] => 1
    [Status] => Accepted
    [transid] => 0
)

答案 1 :(得分:1)

最简单的方法可能是遍历每一行,并将其构建为一个简单的键/值数组:

$results = [];

foreach (explode("\n", $string) as $line) {
  list ($key, $value) = explode('=', $line, 2);
  $results[$key] = $value;
}

echo $results['Status']; // Accepted

答案 2 :(得分:0)

您可以按如下方式提取卷曲响应的内容,

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
// ... 

$response = curl_exec($ch); // Curl response

// After your curl response
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$body = substr($response, $header_size);
curl_close($ch);

var_dump($body);