2017-09-14 10 views
0

내 API에는 두 가지 응답이 있습니다. 받은 텍스트 응답에서 데이터를 가져 와서 변수로 저장할 필요가 있습니다.PHP에서 가능한 두 가지 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 응답 :

가 1 가능한 응답의 경우
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 호출의 첫 번째 가능한 응답을받을 때, 나는 항상 마지막 줄에 오류가 발생할 수 (에코 ....), 다음과 같은 :

(!) 공지 사항 : 정의되지 않은 변수 : 상태
는() 공지 사항 :! 정의되지 않은 변수 :
상태가 myref, 내 참조 ID는

입니다하지만 더 문제는 내가 2 응답을받을 수 없을 때. 내가 원하는대로 보여줍니다

상태 요청 오류는, 내 참조 ID가 도와주세요 (501)

입니다!

+2

json과 같은 더 나은 형식으로 API 응답을 보내지 않는 이유는 무엇입니까? 심지어 XML이 더 좋을 것입니다. 그런 수동 파싱을 ​​필요로하는 커스텀 응답을 갖는 것이 이상하게 보입니다. –

+0

'$ rStatus' = '귀하의 요청을 수락했습니다.'와 일치하지 않습니다. Magnus Eriksson과 동의합니다. API로부터 좀 더 정상적인 응답을 만드십시오. – aynber

+0

... 심지어 더 나빠질 수도 있습니다 ... 요청이 수락되었는지 여부에 따라 실제로 _two different_ 및 맞춤형 형식이 있습니다. –

답변

3

가장 효율적인 방법은 아니지만 JSON 또는 이와 비슷한 형식을 사용해보십시오.

$response = preg_match('/([\w\s]+) ([\w]+)/', $output, $res); 

$response = preg_match('/\w+ \w+/is', $output, $res); 

에 테스트

$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); 
} 
+0

고마워,하지만 preg_match가 더 빠르다. strstr – tsv

+1

@tsv 사실이 아니라고 말하는 것은 아니지만,이 상황에 맞는 그 문장에 대한 참고 자료가 있는가? –

+1

@tsv 그럴 수도 있겠지 만 이것을 확인하십시오 https://stackoverflow.com/a/6433513/2394254 – mega6382

0

당신은 변경해야합니다 정규 표현식 :

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" 
} 

기타 권고 사항 :

어쨌든, 여기에 솔루션입니다
  1. ^및 $ (일반 부분의 시작과 끝)을 사용하기 위해 테스트 전에 응답을 없앱니다.
  2. 사용 ===이 경우에는 == 대신
  3. 체크가 존재합니다. $ res [1]; 전에 $ rstatus = $ res [1];