Belicoff Belicoff - 1 year ago 113
PHP Question

Extract values from JSON array

I have a problem with a decoded JSON response: I don't know how to extract every value from the JSON decoded array in PHP.

My script is like this:

$adresse= $_POST['address'];
$url = 'http://my/host/folder/api';
$data = array(
"value" => $adresse,
$data_string = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "some_user:somepassword");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER,
'Content-Length: ' . strlen($data_string))
$resp = curl_exec($ch);
$json_response = var_dump(json_decode($resp, true));
echo 'test = '.$json_response[1]['zipcode'];

This code returns an array like this:

array(1) {
["eligibilities"]=> array(1) {
[0]=> array(2) {
["address"]=> array(5) {
["zipcode"]=> string(5) "60000"
["city"]=> string(9) "SomeCITY"
["streetName"]=> string(17) "SomeSTreetName"
["streetNumber"]=> string(2) "17"
["idRA"]=> string(10) "SomeIDRA"
["broadBand"]=> array(5) {
["eligible"]=> bool(true)
["type"]=> string(10) "SomeType"
["maxDownstream"]=> int(20000)
["maxUpstream"]=> int(1000)
["tvEligible"]=> bool(false)

I want to parse every value in this array into variables so I can work with the result.

Answer Source

Be aware that var_dump does not return a value, so when you do this:

$json_response = var_dump(json_decode($resp, true));

... then $json_response will be null.

To get access to these inner values, don't forget that there are multiple nested levels involved in your data, and you need to mention the key of each level. So do this:

$result = json_decode($resp, true);
echo 'test = ' . $result['eligibilities'][0]['address']['zipcode'];

NB: don't call your variable $json_responce after the json_decode, because then it is no longer JSON, but a native PHP array.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download