Last active
December 8, 2022 11:44
-
-
Save hungneox/03f807a1b1ea8fe422433ac1d81dc89b to your computer and use it in GitHub Desktop.
Laravel translation to Json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<? | |
# 1 | |
foreach (glob(resource_path() . '/lang/*/*.php') as $file) { | |
preg_match('#^.*/([A-z]*)/([A-z]*).php$#', $file, $matches); | |
$trans[$matches[1]][$matches[2]] = require($file); | |
} | |
foreach ($trans as $lang => $translations) { | |
$fileContents = sprintf('var trans = %s;', json_encode($translations)); | |
file_put_contents(public_path() . '/js/trans.' . $lang . '.js', $fileContents); | |
} | |
#2 Using Laravel Collection | |
$files = collect(File::files(resource_path('lang/*'))); | |
$trans = $files->reduce(function($trans, $file) { | |
$folder = basename(dirname($file)); | |
$name = File::name($file); | |
$trans[$folder][$name] = require($file); | |
return $trans; | |
}, []); | |
collect($trans)->each(function($item, $lang) { | |
$fileContents = sprintf('var trans = %s;', json_encode($item)); | |
File::put(public_path() . '/js/trans.' . $lang . '.js', $fileContents); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment