php parsing Json to variable -


this question has answer here:

i need assistance parsing json variables using php. googled , check through lots of howtos without success. think problem format json in.

here 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" "data" begins.

for example, need capture username, hostname , port variable can call later if want display on page.

you want use json_decode(). full documentation method can found in php manual.

from manual:

takes json encoded string , converts php variable.  returns value encoded in json in appropriate php type. values true, false , null returned true, false , null respectively. null  returned if json cannot decoded or if encoded data deeper  recursion limit. 

i typically use json validator test if json valid. when testing json, looks alright. may want set second parameter of json_decode() true activate associative processing (if have not already) structures in same format. default, associative structs parsed objects, can cause data type change on structure of payload.

in case, access 1 of variables in data portion by:

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

where used associative flag, access using array syntax:

$parsed = json_decode($string, true); $id = $parsed['response']['data'][0]['id']; 

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -