【发布时间】:2017-09-14 23:58:41
【问题描述】:
我的 API 有两种可能的响应。我需要从收到的文本响应中获取数据并将它们存储为变量。
API 调用:
$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 响应:
REQUEST ACCEPTED your ref=<myref> system_reference=<sysref>
Or,
REQUEST ERROR errorno=<error>;your ref=<myref>;system_reason=<sysreason>
如果出现第一个可能的响应,我需要获取如下数据:
$status = "REQUEST ACCEPTED";
$myref = "501";
$sysref = "BA01562";
如果出现第二种可能的响应,我需要获取如下数据:
$status = "REQUEST ERROR";
$error = "25";
$myref = "501";
$sysreason = "Duplicate request";
我试过了:
$response = preg_match('/([\w\s]+) ([\w]+)/', $output, $res);
$rstatus = $res[1];
if ($rstatus == "REQUEST ACCEPTED")
{
$raccepted = preg_match('/([\w\s]+) your ref=([\d]+) system_reference=([\w]+)/', $output, $matches);
$status = $matches[1];
$myref = $matches[2];
$sysref = $matches[3];
}
elseif ($rstatus == "REQUEST ERROR")
{
$rerror = preg_match('/([\w\s]+) errorno=([\d]+);your ref=([\d]+);system_reason=([\w\s]+)/', $output, $matches);
$status = $matches[1];
$error = $matches[2];
$myref = $matches[3];
$sysreason = $matches[4];
}
echo "Status is $status, My Ref ID is $myref";
现在,当我从 API 调用中获得第一个可能的响应时,我总是在最后一行(回显 ....)上得到错误,如下所示:
( ! ) 注意:未定义变量:status
( ! ) 注意:未定义变量:myref
状态是,我的参考 ID 是
但是当我收到第二个回复时没有问题。它显示为我想要的:
状态为 REQUEST ERROR,我的 Ref ID 为 501
请帮忙!
【问题讨论】:
-
为什么不把 API 响应做成更好的格式,比如 json?甚至 XML 会更好。有一个需要手动解析的自定义响应似乎很奇怪。
-
$rStatus=REQUEST ACCEPTED your,所以它不会匹配。我同意 Magnus Eriksson 的观点,从你的 API 中创建一个更理智的响应。 -
...更糟糕的是...您实际上有 两种不同的和自定义格式,具体取决于请求是否被接受。
标签: php preg-match preg-split