我有一个在不同语言之间切换的选项,它工作得非常好-问题是,url保持不变,如果链接在特定的语言选择中共享,我需要使其动态。你知道我该如何实现它吗?
LanguageSwitcher.php
<?php
session_start();
if($_GET['la']){
$_SESSION['la'] = $_GET['la'];
header('Location:'.$_SERVER['PHP_SELF']);
exit();
}
switch($_SESSION['la']){
case "en":
require('lang/en.php');
break;
case "dk":
require('lang/dk.php');
break;
default:
require('lang/en.php');
}
?>下拉列表:
<li><a class="dropdown-item" href="index.php?la=en"><img class="ml-3" src="assets/images/flag_uk.png" alt="<?=$lang['lang-en'];?>" title="<?=$lang['lang-en'];?>" style="width: 25px;"/><span class="ml-3"><?=$lang['lang-en'];?></span></a></li>
<li><a class="dropdown-item" href="index.php?la=dk"><img class="ml-3" src="assets/images/flag_dk.png" alt="<?=$lang['lang-dk'];?>" title="<?=$lang['lang-dk'];?>" style="width: 25px;"/><span class="ml-3"><?=$lang['lang-dk'];?></span></a></li>发布于 2020-11-19 20:30:00
主要要求不是将语言存储在会话中,而是始终在URL中提供语言,这是一项很小的工作,因为您需要更新所有页面上的所有URL。
有两种方式浮现在脑海中,决定选择哪一种取决于个人偏好。
使用GET / REQUEST
https://example.com/subpage?la=en
几乎不需要任何管理工作
更新所有页面上的所有URL,使其包含如下语言:
https://example.com/subpage?la=<?= htmlspecialchars($_GET['la']) ?>注意:htmlspecialchars会转换特殊的超文本标记语言字符以防止。
示例:
index.php
<?php
switch ($_GET['la']) {
default:
// no break ('en' is default)
case 'en':
require('lang/en.php');
break;
case 'dk':
require('lang/dk.php');
break;
}lang/en.php
<!-- some beautiful HTML content here -->
Visit us at https://example.com/subpage?la=<?= htmlspecialchars($_GET['la']) ?>
<!-- another beautiful HTML content here -->使用请求路由器
https://example.com/en/subpage
可以通过使用针对特定情况的库(there are plenty in the wild)或使用framework (最好是micro framework开始)来实现。我个人推荐Slim,一个非常简单但功能强大的PHP微框架。
安装你选择的库或框架(大多数使用composer -阅读他们的文档了解如何做)。然后,更新所有页面上的所有URL以包含语言,如下所示:
https://example.com/en/subpage示例(针对Slim):
index.php
<?php
use Slim\Factory\AppFactory;
require __DIR__ . '/../vendor/autoload.php';
$app = AppFactory::create();
$app->any('/en[/{path:.*}]', function ($request, $response, array $args) {
// you can also directly put code here,
// use the $request and $response objects
// or many other helper classes and methods
require 'lang/en.php';
});
$app->any('/dk[/{path:.*}]', function ($request, $response, array $args) {
// you can also directly put code here,
// use the $request and $response objects
// or many other helper classes and methods
require 'lang/dk.php';
});
$app->run();lang/en.php
<!-- some beautiful HTML content here -->
Visit us at https://example.com/en/subpage
<!-- another beautiful HTML content here -->对翻译机制的一点补充说明
有一种先进的翻译内容的方法,它非常适合上面提到的方法。也就是说,通过将所有可翻译内容包装到方法调用中,方法调用随后查找翻译文件并返回所提供的语言设置的翻译内容。框架通常默认提供此机制(如Symfony's Translation或Laravel's Localization)。
它与原始问题没有直接关系,但值得一提和阅读。
https://stackoverflow.com/questions/64893219
复制相似问题