0

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']; 
localheinz
  • 9,179
  • 2
  • 33
  • 44
snowflakes74
  • 1,307
  • 1
  • 20
  • 43
  • 6
    You might want to check out [PHP's JSON functions](http://php.net/manual/en/book.json.php). – domsson Sep 07 '17 at 12:54
  • What are the string's origins? It sure looks like JSON and if it is, you should be using `json_decode()` – Michael Berkowski Sep 07 '17 at 12:54
  • Are you sure that `$output` is JSON object? Maybe it's just a JSON-like string. – ventaquil Sep 07 '17 at 12:54
  • Accidentally voted to close as duplicate, but referenced the wrong question. This is definitely a duplicate of https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php. – localheinz Sep 07 '17 at 13:06
  • Possible duplicate of [How do I extract data from JSON with PHP?](https://stackoverflow.com/questions/29308898/how-do-i-extract-data-from-json-with-php) – domsson Sep 07 '17 at 13:27

2 Answers2

3

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

Rahul
  • 18,271
  • 7
  • 41
  • 60
0

Thats not string, its json..

$array = json_decode($output,true);
Zeljka
  • 376
  • 1
  • 10