2

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

6
  • 1
    json_decode() returns an array, not an object. $local['translations']['Welcome'] Commented Jul 31, 2015 at 20:44
  • Erm..sorry! Oversaw mixed at php.net^^ Thank You! Commented Jul 31, 2015 at 20:46
  • //Edit: This doesn't work.. Commented Jul 31, 2015 at 20:57
  • var_dump($locale), then. look at what got produced. Commented Jul 31, 2015 at 20:58
  • 1
    If that is your whole json then it is not a valid. Commented Jul 31, 2015 at 21:01

2 Answers 2

1

Figured it out!

Now I figured it out how it works! Thanks alot to you!

Additionals

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! :)

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

@Makville: Sorry but I get this error:Fatal error: Cannot use object of type stdClass as array in C:\xampp\htdocs\API\debug.php on line 7
Try replacing json_decode($json); with json_decode($json, true);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.