user2284703 user2284703 -4 years ago 92
JSON Question

Returning Json Data To PHP Variables

I know there are a lot of similar question as this one on here but the problem I keep running into is that the method in which those other json file arrays are setup is not the same as mine.

What I am trying to do should just be a simple process but as I am not as versed in json arrays and I am other things, the solution is eluding me completely.

I just want to take the data display in a local json file and create PHP variables for each item returned.

The json file is simple and looks something like this...

"titleOne": "Foo",
"textOne": "Bar",
"titleTwo": "Foo",
"textTwo": "Bar"

It will always consist of just these 4 items. Then I use the following PHP to read and decode the file...

$data = file_get_contents ('./data.json');
$json = json_decode($data, true);
foreach ($json as $key => $value) {
foreach ($value as $key => $val) {
echo $key . '====>' . $val . '<br/>';

but this simply outputs the data. I am trying to get each one of these 4 items to become variables. Example...

$textTwo that the variables can be used in a form.

I have found many similar questions as this but the json data is always setup differently resulting in errors as results.

Answer Source

Why not simply define if it's always only 4:

$titleOne = $json[0]['titleOne'];
$textOne = $json[0]['textOne'];
$titleTwo = $json[0]['titleTwo'];
$textTwo = $json[0]['textTwo'];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download