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
答案 0 :(得分:1)
首先,您在此输入的JSON不完整。它缺少打开和关闭花括号。
应该是
{"locale_name": "DE",
"translations": [
{"Welcome": "Willkommen",
"Goodbye": "Auf Wiedersehen"}
]}
php阅读它
$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'];
干杯。
答案 1 :(得分:1)
现在我弄清楚它是如何工作的!非常感谢你!
以下是我的代码:
$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'];
我的JSON文件无关紧要,对于有兴趣的人,请参阅上面Makville的答案。
非常感谢! :)