0

我有一个在语言之间切换的选项,它工作得非常好 - 问题是,该 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>
4

1 回答 1

0

主要要求是不在会话中存储语言,而是始终在 URL 中提供语言,这有点工作,因为您需要更新所有页面上的所有 URL。

有两种方法浮现在脑海中,决定一种取决于个人喜好。

使用GET/REQUEST


  • 导致以下格式的 URL:https://example.com/subpage?la=en
  • 简单,几乎不需要管理工作

更新所有页面上的所有 URL 以包含如下语言:

https://example.com/subpage?la=<?= htmlspecialchars($_GET['la']) ?>

注意:htmlspecialchars转换特殊的 HTML 字符以防止跨站点脚本

例子:

索引.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;
}

语言/en.php

<!-- some beautiful HTML content here -->
Visit us at https://example.com/subpage?la=<?= htmlspecialchars($_GET['la']) ?>
<!-- another beautiful HTML content here -->

使用请求路由器


  • 导致以下格式的 URL:https://example.com/en/subpage
  • 高级,需要一些管理工作和阅读

可以通过针对特定情况使用库(野外有很多)或使用框架来实现,最好是一开始就使用微框架。我个人的推荐是Slim,一个非常简单但功能强大的 PHP 微框架。

安装您选择的库或框架(大多数使用作曲家- 阅读他们的文档以了解如何做到这一点)。然后,更新所有页面上的所有 URL 以包含如下语言:

https://example.com/en/subpage

示例(对于Slim):

索引.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();

语言/en.php

<!-- some beautiful HTML content here -->
Visit us at https://example.com/en/subpage
<!-- another beautiful HTML content here -->

翻译机制的一点旁注


有一种翻译内容的高级方法,非常适合上述方法。也就是说,通过将所有可翻译内容包装到方法调用中,然后查找翻译文件并返回所提供语言设置的翻译内容。框架通常默认提供这种机制(例如Symfony 的 TranslationLaravel 的 Localization)。

它与原始问题没有直接关系,但值得一提和阅读。

于 2020-11-19T12:30:00.230 回答