简体   繁体   中英

Language PHP array - elegant way to pass to Javascript

I have a database with strings and which language this string belongs. A string has a unique name, which I use to identify it, and then a translation for each language.

With PHP, I get this information from the database and store it in an associative array like:

$languages['strings']['lang']['unique_string_name'] = $translation;

Now, as I want my Javascript code to be translated too, I need to pass it to. I've tried doing it in JSON, but some $translation have quotes and double quotes, and it's a hell to escape and get it all correct - because escaping just escapes the whole JSON string, not only translation.

So, what I've done is loop the whole array and echoing the $translation in a Javascript associative array again, but this time with addslashes - only the translation.

However, if I look to the Source Code, I see 600 lines of Javascripts entries, one for each translation (of course, this has nothing strange, just simply UGLY).

I was wondering if there's a much cleaner way of passing this translation array to my Javascript code without having to loop the PHP array and echo it to a JS variable.

Thanks for your time and answers!

All you really need is:

<script type="text/javascript">
var languages = <?php echo json_encode($languages); ?>;
</script>

You'll end up with an exact duplicate of your PHP array in JS, so

echo $languages['strings']['lang']['unique_string_name']; // PHP
alert(languages.strings.lang.unique_string_name); // JS

will both bring up the same translation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM