-2

I need assistance with parsing json to variables using php. I googled and check through lots of howtos but without success. I think the problem is with the format my json is in.

Here is the json:

{"type":"success","response":{"data":[{"id":5,"username":"account2","hostname":"testapp.net","port":8080,"status":"enabled","email":"john@yourmomma.com","servertype":"IceCast","hostref":"0.0.0.0"},{"id":4,"username":"account1","hostname":"testapp2.net","port":8082,"status":"disabled","email":"john@yourmomma.com","servertype":"ShoutCast2","hostref":"0.0.0.0"}],"message":"2 account(s)"}}

The tricky part starts after "response" where "data" begins.

For example, I basically need to capture username, hostname and port into a variable so that I can call it up later if I want to display it on another page.

johnslippers
  • 81
  • 1
  • 16
  • @Machavity Not a duplicate of the article you supplied as the JSON format was different and that is what made the task difficult. My issue was the array syntax. Next time I will include my code and try to explain better. – johnslippers May 17 '17 at 15:23

1 Answers1

1

You will want to use json_decode(). The full documentation for the method can be found in the PHP Manual.

From the manual:

Takes a JSON encoded string and converts it into a PHP variable.

Returns the value encoded in json in appropriate PHP type. Values true,
false and null are returned as TRUE, FALSE and NULL respectively. NULL is 
returned if the json cannot be decoded or if the encoded data is deeper than 
the recursion limit.

I typically use a JSON Validator to test if the json is valid. When testing your json, it looks to be alright. You may want to set the second parameter of json_decode() to true to activate associative processing (if you have not already) so that all structures are in the same format. By default, associative structs are parsed as objects, which can cause the data type to change over the structure of the payload.

In your case, you would access one of the variables in the data portion by:

$parsed = json_decode($string);
$id = $parsed->response->data[0]->id;

Where is you used the associative flag, you would access it fully using array syntax:

$parsed = json_decode($string, true);
$id = $parsed['response']['data'][0]['id'];
Mike
  • 1,968
  • 18
  • 35
  • 1
    While not incorrect, there's no code in your answer. This could be summed up as "Read the manual" – Machavity Mar 28 '17 at 14:00
  • 1
    @Machavity In fairness, "read the manual" is the correct answer. – ceejayoz Mar 28 '17 at 14:04
  • @Mike: Thank you. Your answer solved my issue. The error I got before was "Array to string conversion" but that was because I was missing the [0] part. I can't mark your answer as correct because my reputation is below 15. – johnslippers Mar 29 '17 at 08:54