Skip to content
Advertisement

How to retrieve certain data in string?

Hello may i know how to retrieve data in string?

$url = 'test url';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$info = curl_getinfo($ch);
$response = curl_exec($ch);
curl_close ($ch);

echo 'Response: ';
echo gettype($response);
echo '<br>';

echo($response);

Output :

Response: string
TRANSACTION_ID=abc123
MERCHANT_ACC_NO=M213213
TXN_STATUS=A
TRAN_DATE=2020-07-20
CAPTURE_DATE=2020-07-20
SALES_DATE=2020-07-20 
RESPONSE_CODE=1
RESPONSE_MESSAGE=Success

As you can see the output of the code is as shown above. This is my first time to encounter this kind of output because usually I get json as the output. So my question is may I know how to retrieve the RESPONSE_MESSAGE in the output or may I know how to convert the output to array or json so that I can easily retrieve the data. Sorry for asking this I’m quite new with this PHP and CURL function.

Advertisement

Answer

You can explode to lines and explode the lines to parts in a foreach.
Edit: I realized the “Response:” was actually outputted manually.
Changed the code to slice the array from second item instead.

foreach(array_slice(explode("n", $str), 1) as $line){
    $temp = explode("=", $line);
    $res[$temp[0]] = $temp[1];
}

Output:

array(8) {
  ["TRANSACTION_ID"]=>
  string(6) "abc123"
  ["MERCHANT_ACC_NO"]=>
  string(7) "M213213"
  ["TXN_STATUS"]=>
  string(1) "A"
  ["TRAN_DATE"]=>
  string(10) "2020-07-20"
  ["CAPTURE_DATE"]=>
  string(10) "2020-07-20"
  ["SALES_DATE"]=>
  string(11) "2020-07-20 "
  ["RESPONSE_CODE"]=>
  string(1) "1"
  ["RESPONSE_MESSAGE"]=>
  string(7) "Success"
}

https://3v4l.org/evdMO

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement