First of all I am a very new to PHP
so forgive me.
I want to take a JSON
response and split it up. This will be coming from a $_POST
variable, however I am trying to test out the would be response in a hard coded variable. The problem is I can't even get it to print in order to see that I'm starting this out right.
$json =
'({
"array":
[
"Store #: 00608",
"Phone #: null",
"Address: 3014 N. SCOTTSDALE RD.",
"City: SCOTTSDALE",
"Zip: 85251",
"State: AZ",
"Height: 6`4",
"Weight: 230",
"Ethnicity: White",
"Age: 23",
"Eye Color: Blue",
"Favorite Food: Thai",
"Comments: awesome"
]
})';
$data = json_decode($json,true);
$pieces = explode(":", $data);
for ($i = 0; $i < count($data['array']); $i++) {
echo $pieces[$i];
}
When I launch this in my browser I get a blank screen, with no errors. End goal is to store these into a PHP
array as 'Store #', '00608'
etc.
Anyways, what am I doing wrong?
I think this is pretty much what you're looking for.
$json =
'{
"array":
[
"Store #: 00608",
"Phone #: null",
"Address: 3014 N. SCOTTSDALE RD.",
"City: SCOTTSDALE",
"Zip: 85251",
"State: AZ",
"Height: 6`4",
"Weight: 230",
"Ethnicity: White",
"Age: 23",
"Eye Color: Blue",
"Favorite Food: Thai",
"Comments: awesome"
]
}';
$data = json_decode($json,true);
foreach($data['array'] as $piece) {
$array = explode(': ', $piece);
echo 'Key: '.$array[0].'<br />';
echo 'Value: '.$array[1].'<br />';
echo '<br />';
}
Returns
Key: Store #
Value: 00608
Key: Phone #
Value: null
Key: Address
Value: 3014 N. SCOTTSDALE RD.
Try this JSON.
$json =
'{
"array":
[
"Store #: 00608",
"Phone #: null",
"Address: 3014 N. SCOTTSDALE RD.",
"City: SCOTTSDALE",
"Zip: 85251",
"State: AZ",
"Height: 6`4",
"Weight: 230",
"Ethnicity: White",
"Age: 23",
"Eye Color: Blue",
"Favorite Food: Thai",
"Comments: awesome"
]
}';
Notice I took out your ()!
You have invalid JSON, in that you have parenthesis around the JSON string. Remove those and it should parse correctly.