leo95batista
leo95batista

Reputation: 767

Laravel get the content of a translation file as an array

could you help me with the following question. I need to get the content of a translation file as an array regardless of whether it is a PHP file or a JSON file.

Suppose I have the following structure in my project:

laravel_project/resources/lang/
├── en
├── es
├── file1.php
├── file2.json
...

and I have the following method:

    public function example()
    {
        dd(__('file1', [], '/'));
    }

I get the following result:

array:2 [
  "failed" => "These credentials do not match our records."
  "throttle" => "Too many login attempts. Please try again in :seconds seconds."
]

Which is great since it is the content of the file1.php file, but I wonder how I can get the content of the file2.json file in the same way, because when I do the following:

    public function example()
    {
        dd(__('file2', [], '/'));
    }

I get the following result:

"file2"

The content of the file2.json file is the following:

{
    "A": "My string A",
    "B": "My string B"
}

I mean, it is not returning the content of the file file2.json. Is there an elegant way to achieve what I am trying to do? Basically what I am trying to do is return the content of a translation file regardless of whether it is a PHP file or a JSON file. Thank you very much in advance.

Upvotes: 3

Views: 2476

Answers (2)

patricus
patricus

Reputation: 62278

Testing in Laravel 7x shows that your json file contents can be accessed like:

dd(__('*', [], 'file2'));

Given this, you would still need to come up with a way to determine if you're accessing a PHP file or a JSON file. You could do something like:

public function example($file)
{
    // get JSON contents
    $data = __('*', [], $file);

    // if no JSON contents found, get PHP contents
    if ($data == '*') {
        $data = __($file, [], '/');
    }

    return $data;
}

NB: this is using the translator in a way that is undocumented and not intended. There is no guarantee a future "non-breaking" change won't break this.

Another option you have is to extend and override the framework's FileLoader and/or Translator to add in the functionality you're looking for. Bind your override classes into the aliases in the container, and then your custom code will be used.

Upvotes: 3

Alex Deaf
Alex Deaf

Reputation: 51

You can use

 $yourJsonAsArray = json_decode(implode(file($filename)), true);

Upvotes: 0

Related Questions