dongqie2010
2017-10-04 10:34
浏览 184
已采纳

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

I am getting the response from curl as follows in a string:

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

I want to get individual variables like status= Accepted so that i can able to store those in my database. Any help will be highly appreciable.

图片转代码服务由CSDN问答提供 功能建议

我从字符串中得到curl的响应如下:

  <代码>接受= AVSAUTH:TEST ::: 829649376:N :: U 
ENTRYMETHOD = KEYED 
historyid = 829649376 
MERCHANTORDERNUMBER = 14700000186 
orderid = 646526156 
PAYTYPE =万事达
recurid = 0 
refcode = 829649376-TEST 
result =  1 
Status = Accepted 
transid = 0 
   
 
 

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

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • dqwr32867 2017-10-04 10:59
    已采纳

    preg_match is your friend:

    <?
    $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 will be an hash Array:

    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
    )
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • du59131 2017-10-04 11:02

    The easiest way might be to loop over each line, and build it into a simple key/value array:

    $results = [];
    
    foreach (explode("
    ", $string) as $line) {
      list ($key, $value) = explode('=', $line, 2);
      $results[$key] = $value;
    }
    
    echo $results['Status']; // Accepted
    
    评论
    解决 无用
    打赏 举报
  • dotibrb048760 2017-10-04 11:03

    You can extract content of curl response as follows,

    $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);
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题