doumianfeng5065 2017-09-13 19:20 采纳率: 0%
浏览 145

如何从PHP中的API调用的纯文本响应中获取数据?

I'm getting API response in plain text. I need to grab data from that text response and need to store them as variables.

API Calling:

  $url="http://91.101.61.111:99/SendRequest/?mobile=9999999999&id=11011&reqref=501";
  $request_timeout = 60;
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_TIMEOUT, $request_timeout);
  curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $request_timeout);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $output = curl_exec($ch);
  $curl_error = curl_errno($ch);
  curl_close($ch);  

API response in plain text:

REQUEST ACCEPTED your ref=501 system_reference=BA01562    

I need to grab data from the above plain text response as variables, like below:

$status = "REQUEST ACCEPTED";  
$myref = "501";  
$sysref = "BA01562";  

I have tried:

$explode1 = explode(" ", $output);      
$explode2 = explode("=", $explode1[3]);
$explode3 = explode("=", $explode1[4]);

$status = $explode1[0]." ".$explode1[1];
$myref = $explode2[1];
$sysref = $explode3[1];

I know this is not a proper way to do this. But I am not able to figure out the proper way to do it since I'm a newbie.

Please help! Thank you!

  • 写回答

1条回答 默认 最新

  • douzhengyi5022 2017-09-13 21:24
    关注

    you can use a preg_match, something like:

    $rc = preg_match('/([\w\s]+) your ref=([\d]+) system_reference=([\w]+)/', $plain_response, $matches);
    if ($rc)
    {
        $status = $matches[1];  
        $myref = $matches[2];  
        $sysref = $matches[3];  
    }
    

    but of course, just as @Don't panic said, you need a bit more knowledge of the API, to be sure about parsing. The example i gived is a bit childish. Anyway, when you will be sure about the format, use regexp with preg_match.

    评论

报告相同问题?

悬赏问题

  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频