【发布时间】:2022-11-23 04:42:57
【问题描述】:
我想写我自己的小翻译功能。
我的 JSON 文件如下所示:
{
"start": {
"body": {
"headline": "Hello, world!"
}
}
}
在我的 PHP 前端中,我只想为翻译后的字符串编写占位符。所以我做
<h1><?php trans('start.body.headline'); ?></h1>
我的 PHP 函数很简单,看起来像:
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;
}
但我没有得到结果。
我的函数中的 $string 是正确的:
start->body->headline
当我写的时候:
echo $json->start->body->headline;
我得到“你好,世界”。
echo $json->$string;
相同但不起作用。为什么?
【问题讨论】:
标签: php json object nested placeholder