Pratyush Pranjal
Pratyush Pranjal

Reputation: 554

converting api response to php string

Below is my code, I am trying to get particular api response (msg,amt) in php string. ........................................................................................................................................

$key = "XXXXX";
$mykey = "XXXXX";
$command = "Check";
$value = "5454355435"; 


$r = array('key' => $key , 'value' => $value, 'command' =>  $command);

$qs= http_build_query($r);
$wsUrl = "https://info.service-provider.com";

$c = curl_init();
curl_setopt($c, CURLOPT_URL, $wsUrl);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $qs);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$o = curl_exec($c);
if (curl_errno($c)) {
  $sad = curl_error($c);
  throw new Exception($sad);
}
curl_close($c);

$valueSerialized = @unserialize($o);
if($o === 'b:0;' || $valueSerialized !== false) {
  print_r($valueSerialized);
}

print_r($o);

RESPONSE:

{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}

Upvotes: 0

Views: 946

Answers (2)

axldns
axldns

Reputation: 55

This response looks like JSON format. Pass this response string to php method json_decode like:
$response = json_decode($yourResponseString,true);
and then you should be able to access it's properties like a regular associative array:
$msg = $response['msg'];

Upvotes: 0

Anand Solanki
Anand Solanki

Reputation: 3425

Your string is in json format. To get value from it, you should convert it into an array like this:

$json = '{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}';

$array = json_decode($json, true);

echo '<pre>'; print_r($array);

Your array will look like this:

Array
(
    [status] => 1
    [msg] => 1 out of 1 Transactions Fetched Successfully
    [transaction_details] => Array
        (
            [2767712494] => Array
                (
                    [mihpayid] => 268999084
                    [request_id] => 
                    [ref_num] => 020814301298
                    [amt] => 1.00
                    [txnid] => 5454355435
                    [additional_charges] => 0.00
                    [productinfo] => SHIRT
                )

        )

)

To get msg you should write like this:

echo $array['msg'];

You can get more information from json_decode

Let me know for more help.

Upvotes: 2

Related Questions