snowflakes74
snowflakes74

Reputation: 1307

How can I decode a JSON string in PHP?

I am trying to read a string into an array in PHP, but it doesn't work for me.

The string I would like to read:

$output = {"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}

The code I am using:

$arr = explode(',', $output);

foreach($arr as $v) {
    $valarr = explode(':', $v);
    preg_match_all('/"(.*?)"/', $valarr[0], $matches);
    $narr[$matches[1][0]][$matches[1][1]] = $valarr[1];
}

Specifically, I would like to access the value for 'message' (i.e., 'Approved').

I tried this, but it still fails:

echo 'MESSAGE ' .  $arr['message']; 

Upvotes: 0

Views: 79

Answers (2)

Rahul
Rahul

Reputation: 18557

Here is working code,

  $arr = '{"message":"Approved","responseCode":"0","responseCodeDesc":"Transaction Successful"}';
  $arr = json_decode($arr, true);
  echo $arr['message'];
  print_r($arr);

Here is working link

Upvotes: 3

Zeljka
Zeljka

Reputation: 376

Thats not string, its json..

$array = json_decode($output,true);

Upvotes: 0

Related Questions