0

I would like to localize my website so I'm making a JSON array containing variables for 3 different languages, like this:

{
    "i18n_en":
    [
        "good"
    ],
    "i18n_de":
    [
        "gut"
    ],
    "i18n_ru":
    [
        "хорошо"
    ]
}

And so on... Obviously there's more words in there - and that's how I'm trying to use this in PHP:

<?php
    $json = file_get_contents('/lang/i18n_en.json', true);
    $obj = json_decode($json);
    echo $obj[0]["good"];
?>

The above code echoes nothing. How can I echo a specific item from a specific JSON array using php? Something like:

For example I would like to echo the value of the key "good" from the 118n_de array on one page and echo the same key's value from the i18n_ru array on another one. I'd really appreciate your help.

Johny P.
  • 648
  • 1
  • 9
  • 31
  • Use json_decode to decode the JSON and make it usable. – kainaw Apr 26 '16 at 18:00
  • I edited the code in my question. But I get the following error in PHP: `Warning: Illegal string offset 'good' in json.php` – Johny P. Apr 26 '16 at 18:05
  • *Needed, since I also have to (...)* No. Bad way. If your JSON is valid, json_decode strip slashes for you. Otherwise, [check if your JSON is valid](http://jsonlint.com/). – fusion3k Apr 26 '16 at 18:06
  • @JohnyP.Use json_decode, not stripslashes. Then, use something like print_r to see the actual structure of the resulting object. It may be that $obj is actually an object, not an array. – kainaw Apr 26 '16 at 18:07
  • not `$obj[0]["good"]` (`$obj` is a string). try with `$json[0]->good` – fusion3k Apr 26 '16 at 18:08
  • @kainaw my json code is similar to the one in the question, but there are more objects in those arrays. fusion3k just found out there's an error, I'll try to fix it. – Johny P. Apr 26 '16 at 18:09
  • If it is similar, it is **NOT VALID**. With not valid JSON, you can not obtain valid array/object. – fusion3k Apr 26 '16 at 18:10
  • I edited my question's JSON so that it is valid. What PHP code to use to echo the first index of the array? – Johny P. Apr 26 '16 at 18:20

0 Answers0