我将所有网站翻译短语存储在一个XML文件中,我在每页顶部使用PHP读取该文件。
这个XML是以某种方式缓存的吗?或者每次重新加载新页面时是否从服务器读取文件?在这种情况下,这对性能有害吗? 将PHP变量中的所有翻译短语存储在每个页面顶部的PHP文件中会更好吗?
评论中要求的代码如下。
在每页的顶部:
<?php session_start(); ?>
<?php include 'lib/phrases.php'; ?>
<?php $phrs = new Phrases(); ?>
phrases.php:
<?php
class Phrases{
//load phrases to PHP:
public function load_phrases($lang_id) {
$xml = new DomDocument('1.0');
//path to language directory
$lang_path=("phrases/".$lang_id.'.xml');
$xml->load($lang_path);
//phrases are inside page tags, first we must get these
$page = $xml->getElementsByTagName('page');
$page_num=$page->length;
for($i = 0; $i < $page_num; $i++) {
$page=$xml->getElementsByTagName('page')->item($i);
//get phrase tags and store them into array
foreach($page->getElementsByTagName('phrase') as $phrase) {
$phrase_name = $phrase->getAttribute('name');
$phrases[$phrase_name] = $phrase->firstChild->nodeValue;
$phrases[$phrase_name] = str_replace('\n','<br/>',$phrases[$phrase_name]);
}
}
$this->phrases=$phrases;
}
//phrases are accessed
public function lang_id() {
//determine page language
$lang = 'en';
switch(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2)){
case 'sv':
$lang = 'sv';
break;
case 'fr':
$lang = 'fr';
break;
case 'it':
$lang = 'it';
break;
case 'no':
$lang = 'no';
break;
default:
$lang = 'en';
}
$lang_id = isset($_COOKIE['lang']) ? $_COOKIE['lang'] : $lang;
//set the language cookie and update cookie expiration date
if(!isset($_COOKIE['lang'])) {
$expiration_date=time()+3600*24*7;
setcookie('lang',$lang_id,$expiration_date,'/');
}
if(!isset($lang_id) || $lang_id == NULL) $lang_id = 'en';
return $lang_id;
}
public function change_lang($lang_id) {
setcookie('lang',$lang_id,$expiration_date,'/');
}
//construct function
public function __construct() {
$this->load_phrases($this->lang_id());
}
}
?>
XML文件的开头:
<?xml version="1.0" encoding="UTF-8"?>
<language name="en">
<page name="header">
<phrase name="header_home">Home</phrase>
<phrase name="header_blogs">Blogs</phrase>
<phrase name="header_readmore">Read More</phrase>