1

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?

1
  • json_decode($string, true). Commented May 17, 2018 at 12:28

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. It worked. The brackets are missing because the return was too long so i cut it to fit better here.
@LuanWincardt glad to help you :):)
0

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.