How to decode a JSON string in PHP?
I have a JSON string that looks something like this:
{"addresses":{"address":[{"@array":"true","@id":"888888","@uri":"xyz","household":{"@id":"44444","@uri":"xyz"},"person":{"@id":"","@uri":""},"addressType":{"@id":"1","@uri":"xyz","name":"Primary"},"address1":"xyz","address2":null,"address3":null,"city":"xyz","postalCode":"111111"}]}}
What would be the PHP to decode this and place address1
, address2
, address3
, city
, and postalCode
into session variables?
So far I tried this but it's not working:
$results = json_decode(strstr($address, '{"addresses":{"address":[{'), true);
$_SESSION['address1'] = $results['address']['address1'];
Thanks!
print_r
is your friend for figuring out JSON structure.
<?php
$addresses = json_decode('{"addresses":{"address":[{"@array":"true","@id":"888888","@uri":"xyz","household":{"@id":"44444","@uri":"xyz"},"person":{"@id":"","@uri":""},"addressType":{"@id":"1","@uri":"xyz","name":"Primary"},"address1":"xyz","address2":null,"address3":null,"city":"xyz","postalCode":"111111"}]}}');
$_SESSION['address1'] = $addresses->addresses->address[0]->address1;
$_SESSION['address2'] = $addresses->addresses->address[0]->address2;
$_SESSION['address3'] = $addresses->addresses->address[0]->address3;
$_SESSION['city'] = $addresses->addresses->address[0]->city;
$_SESSION['postalCode'] = $addresses->addresses->address[0]->postalCode;
print_r($_SESSION);
Results in:
Array
(
[address1] => xyz
[address2] =>
[address3] =>
[city] => xyz
[postalCode] => 111111
)
json_decode will decode a json-formatted string into a PHP object.
Try this:
$results = json_decode($address);
$results['address1'] = $results->addresses->address[0]->address1;
$results['address2'] = $results->addresses->address[0]->address2;
$results['address3'] = $results->addresses->address[0]->address3;
$results['city'] = $results->addresses->address[0]->city;
$results['postalCode'] = $results->addresses->address[0]->postalCode;
Edit - updated, I misread your JSON at first.
Note that those "@array" and "@id" fields are invalid JSON notation, and technically they lead to unspecified behavior in JSON parsers.
Why not decode the whole JSON string and then get what you need?
$address = '{"addresses":{"address":[{"@array":"true","@id":"888888","@uri":"xyz","household":{"@id":"44444","@uri":"xyz"},"person":{"@id":"","@uri":""},"addressType":{"@id":"1","@uri":"xyz","name":"Primary"},"address1":"xyz","address2":null,"address3":null,"city":"xyz","postalCode":"111111"}]}}';
$results = json_decode($address, true);
$address = $results['addresses']['address'][0];
print $address['address1'];
print $address['address2'];
print $address['postalCode'];