我的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调用获得第一个可能的响应时,我总是在最后一行(echo ....)上得到错误,如下所示:
(!)注意:未定义的变量:状态
(!)注意:未定义的变量:myref
状态是,我的参考ID是
但是当我收到第二个回复时没有问题。它显示我想要的:
状态为REQUEST ERROR,我的参考ID为501
请帮忙!
答案 0 :(得分:3)
这不是最有效的方法,请尝试使用JSON
之类的正确格式。无论如何,这是一个解决方案:
$success = stristr($output, "REQUEST ACCEPTED");
if($success)
{
$data = stristr($output, "ref");
$raccepted = preg_match('/ref=([\d]+) system_reference=([\w]+)/', $data, $matches);
var_dump($matches);
}
else
{
$data = stristr($output, "errorno");
$rerror = preg_match('/errorno=([\d]+);your ref=([\d]+);system_reason=([\w\s]+)/', $data, $matches);
var_dump($matches);
}
答案 1 :(得分:0)
您应该更改正则表达式
$response = preg_match('/([\w\s]+) ([\w]+)/', $output, $res);
到
$response = preg_match('/\w+ \w+/is', $output, $res);
测试:
php > preg_match('/\w+ \w+/is', "REQUEST ACCEPTED your ref=some system_reference=some123", $res);
php > var_dump($res);
php shell code:1:
array(1) {
[0] =>
string(16) "REQUEST ACCEPTED"
}
php > preg_match('/\w+ \w+/is', "REQUEST ERROR errorno=123;your ref=SOMEref;system_reason=reason", $res);
php > var_dump($res);
php shell code:1:
array(1) {
[0] =>
string(13) "REQUEST ERROR"
}
其他建议: