Luan Wincardt
Luan Wincardt

Reputation: 13

How to put an API return string into an array

I have a string that i get from an API and i wish i could put it in a array so i could check the values that came from the return.

String return example:

{
  "code":"000",
  "message":"XXX",
  "date":"2018-05-17",
  "hour":"09:16:09",
  "revision":"",
  "server":"XX",
  "content":{
     "nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
  }
}

What I need:

echo $string['code'];

Javascript has no problem with JSON encode command. But how can I do it with PHP?

Upvotes: 1

Views: 136

Answers (3)

ThomasVdBerge
ThomasVdBerge

Reputation: 8140

Your example string is not valid json, you are missing some closing brackets.

This should be the correct way:

'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'

As for your question. in PHP you can easily use json_decode

Example:

<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';

$decoded_json = json_decode($json, true);
echo $decoded_json['code'];

You can see it working here

Upvotes: 0

Kishen Nagaraju
Kishen Nagaraju

Reputation: 2190

You can decode the JSON string to Array in PHP.

$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);

var_dump($decodedValue);

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

First of all your JSON data seems to be invalid (Some brackets missing). It needs to be like this:-

{
    "code": "000",
    "message": "XXX",
    "date": "2018-05-17",
    "hour": "09:16:09",
    "revision": "",
    "server": "XX",
    "content": {
        "nome": {
            "info": "SIM",
            "conteudo": [{
                "field1": "XXXX",
                "field2": "XX"
            }]
        }
    }
}

Now You need to decode this JSON data and then get data based on the index

$array = json_decode($json,true);

echo $array['code'];

Output:-https://eval.in/1005949

Upvotes: 1

Related Questions