Home > Blockchain >  Get Value from nested JSON File in PHP with Placeholder
Get Value from nested JSON File in PHP with Placeholder

Time:11-27

I want to write my own little translation function.

My JSON File looks like:

{
"start": {
  "body": {
    "headline": "Hello, world!"
   }
  }
}

In my PHP Frontend, i want to write just Placeholders for translated Strings. So id do

<h1><?php trans('start.body.headline'); ?></h1>

My PHP Function is simple and looks like:

function trans($string) {

    if (!isset($_GET['langID']))
        $lang = 'de';
    else
        $lang = $_GET['langID'];

    $str = file_get_contents('lang/'. $lang . '.json');
    $json = json_decode($str);
    $string = str_replace('.', '->', $string);
 
    echo $json->$string;

  }

But I don't get a Result.

The $string in My Function is correctly:

start->body->headline

And when I write:

echo $json->start->body->headline;

I get "Hello, world".

echo $json->$string; 

is the same but doesn't work. why?

CodePudding user response:

becouse you are using the some variable name $string for function parameter , use the other variable name here.

$keyword = str_replace('.', '->', $string);

echo $json->{$keyword};

also you can use return method

function trans($string) {

if (!isset($_GET['langID']))
    $lang = 'de';
else
    $lang = $_GET['langID'];

$str = file_get_contents('lang/'. $lang . '.json');
$json = json_decode($str);
$keyword = str_replace('.', '->', $string);

return $json->{$keyword};
}

and than use short way of echo in html

<h1><?= trans('start.body.headline'); ?></h1>

CodePudding user response:

It doesn't work.

 function trans($someWord) {

    if (!isset($_GET['langID']))
        $lang = 'de';
    else
        $lang = $_GET['langID'];

    $str = file_get_contents('lang/'. $lang . '.json');
    $json = json_decode($str);
    $someWord = str_replace('.', '->', $someWord);
 
    echo $json->$someWord;

}

trans('start.body.headline');

No matter what I use for the string. Output is empty.

  • Related