Reputation: 78
I have searched for almost 30 minutes and still can't find the answer for my problem. So, here is it: I have an JSON-file called "localeDE.l", now I'm trying to print the objects to the website, "locale_name"(type: string) works, but "translations"(type: array) won't work.
My JSON file:
"locale_name": "DE",
"translations": [
{"Welcome": "Willkommen",
"Goodbye": "Auf Wiedersehen"}
]
Here my PHP file:
$file = file_get_contents('localeDE.l');
$locale = json_decode($file);
print_r($locale);
echo "Locale=" . $locale->{'locale_name'};
echo "Translations:";
echo " Welcome:" . $locale->{'translations'}->{'Welcome'};
echo " Goodbye:" . $locale->{'translations'}->{'Goodbye'};
I also tried something like (...) $locale->{'translations.Welcome'};
etc.
Can You help me?
- Felipe Kaiser
Upvotes: 2
Views: 96
Reputation: 628
First the JSON like you typed it here is incomplete. It's missing both opening and closing curly braces.
It should be
{"locale_name": "DE",
"translations": [
{"Welcome": "Willkommen",
"Goodbye": "Auf Wiedersehen"}
]}
The php to read it
$obj = json_decode($json, true);
//to read the locale name
echo $obj['locale_name'];
//to read the translation of welcome
echo $obj['tranlations'][0]['Welcome'];
//to read the tranlation of goodbye
echo $obj['translations'][0]['Goodbye'];
Cheers.
Upvotes: 1
Reputation: 78
Now I figured it out how it works! Thanks alot to you!
Here are my code pieces:
$json = file_get_contents('localeDE.l');
$obj = json_decode($json, true);
echo $obj['locale_name'];
echo $obj['translations'][0]['Welcome'];
echo $obj['translations'][0]['Goodbye'];
And my JSON file is unrelevant, for those who are interested, see the answer of Makville above.
Thanks alot! :)
Upvotes: 1