Skip to content
Advertisement

PHP – html_entity_decode to entire array

I am fetching JSON data for use in my website and I need to echo it, like this:

<?php
    $json = file_get_contents("/lang/translator.php"); // uses preg_replace to remove whitespace/newlines from my actual json file and then echo's it
    $i18n = json_decode($json, true);

    if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
    {
        $arr = 'i18n_en';
    }
    else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
    {
        $arr = 'i18n_ru';
    }
?>

And I use it like this:

<?php echo $i18n[$arr]['string_key']; ?>

The string_key holds in its value either a English or a Russian translation of my site, depending in which JSON array it is.

The problem:

When I upload my JSON file which holds Cyrillic characters (Russian) this happens:

хорошо --> хорошо

Every single Cyrillic character gets converted to HTML entities. So I found out I could use html_entity_decode() to counter that but imagine how time-consuming it is to do this for every single <?php echo $i18n[$arr]['string_key']; ?> call I have in my code. Isn’t there any way around that? I tried passing $i18n to html_entity_decode() but it expects a string, not an array of strings. Any ideas?

My JSON example:

{
    "i18n_en":
    {
        "key0": "value0",
        "key1": "value1"
    },
    "i18n_ru":
    {
        "key0": "value0",
        "key1": "value1"
    }
}

Advertisement

Answer

Once you have set $arr, you could apply html_entities_decode() to every string in the specified language with a foreach loop.

Something like this:

if (htmlentities($_GET['lang'], ENT_QUOTES) == 'en')
{
    $arr = 'i18n_en';
}
else if (htmlentities($_GET['lang'], ENT_QUOTES) == 'ru')
{
    $arr = 'i18n_ru';
}

foreach ($i18n[$arr] as &$myString) {
    $myString = html_entity_decode($myString);
}

Edit. Two posible solutions to fix Warning: Illegal string offset 'i18n_en'.

1:

foreach ($i18n[$arr] as &$myString) {
    if(isset($myString)){
        $myString = html_entity_decode($myString);
    }
}
foreach ($i18n[$arr] as &$myString) {
    $myString = html_entity_decode($myString, ENT_COMPAT, 'UTF-8');
}

Or maybe, both combined. Let me know if this works please.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement