Home php教程 php手册 利用PHP输出控制功能做简繁体转换

利用PHP输出控制功能做简繁体转换

Jun 21, 2016 am 09:07 AM
php session str

控制|转换

【摘 要】 PHP 作为一种公开源代码的脚本语言,其扩充性是非常好的。本文只是对其一个功能的一种应用方式的探讨,并实现了比较完美的同一页面自动简繁体转换功能。希望广大爱好 PHP 的朋友能从中得到启发,做出更好的作品。

本文对PHP的输出控制功能进行了简单介绍并对其在简繁体转化中的应用给出了具体思路和实例。

  一 PHP 输出控制功能介绍

  PHP作为当今流行的脚本语言之一,具有编写简便,执行速度快,扩充性好等优点。PHP的输出信息控制函数可以让你控制你的脚本输出的内容,可以用于许多不同的情况,特别是在你的脚本已经输出信息后需要发送文件头的情况以及需要对输出信息进行编辑处理的地方。输出控制函数不对使用 header() 或 setcookie() 发送的文件头信息产生影响,只对那些类似于 echo()、print() 和 PHP 代码的数据块有作用。

  例 1. 控制输出

  test.php

<?
function test($str){
return str_replace("php2000","y10k",$str);
}
ob_start("test");
echo "hello php2000";
ob_end_flush();
?>


  这个程序在没有输出信息控制的情况下应该输出为

hello php2000

  但通过指定了输出控制函数后,输出变为

hello y10k

  在上面的例子中,使用 echo() 的输出内容将会保存在输出缓冲区中,直到调用了 ob_end_flush()或者脚本运行终止, 然后输出信息由自定义的处理函数进行处理(替换里面的字符串)并返回结果。

  相关函数说明:

ob_start([string output_callback])- 打开输出缓冲区

  所有的输出信息不在直接发送到浏览器,而是保存在输出缓冲区里面,可选得回调函数用于处理输出结果信息。

ob_end_flush - 结束(发送)输出缓冲区的内容,关闭输出缓冲区

  二 简繁体转换的实现

  一般通过对照表的形式实现,相关的文章非常多,这里就不多讲了,只给出其实现代码

<?
function gb2big5($str) {
 global $_gb_big5_;
 $leng = strlen($str)-1;
 for($i = 0; $i<$leng; $i++){
  $h = ord($str[$i]);
  if($h>=160){
   $l = ord($str[$i+1]);
   $gb=($h==161 && $l==64)?" " : substr($_gb_big5_, ($h-160)*510+($l-1)*2, 2);
   $str[$i] = $gb[0];
   $str[$i+1] = $gb[1];
   $i++;
  }
 }
 return $str;
}
?>


  其中:

  $gb_big5_ 保存着big5 的字库对照表
  $str 为要转化的字符串

  三 输出控制函数在简繁体转化中的应用

  目前的大多数网站的简繁体页面转换都是通过各自单独的页面实现的,这样导致在修改简体页面的时候还需要再次修改繁体的页面,不能做到自动同步。而我们提供的这个方法,可以实现同一个页面自动的变换简繁体显示。其实现方法是:

  1、建立简繁体标志,用于指示当前显示的简繁体状态,同时对简繁体状态进行切换

  php2000_gb_big5.php

<?
session_start(); // 打开session 功能,用于在各个页面之间自动传递标志
if(!session_is_registered("php2000_big5")){ // 检查简繁体标志的注册状态
session_register("php2000_big5"); // 注册简繁体标志,简体=0;繁体=1
$php2000_big5=0; // 默认为简体
}
$php2000_big5 = ($php2000_big5+1)%2; // 切换简繁体状态
header("location:".getenv("HTTP_REFERER")); // 返回其调用页面
?>


  2、对页面输出信息进行控制,每个页面都调用这段程序,用于简繁体转换

  require.php(应包括前面第二部分的转换代码,这里略)

<?
Session_start();
function translate_gb2big5($str) {
 $str = gb2big5($str); // 转化为 big5
 $str = str_replace('charset=gb2312', 'charset=big5', $str); // 替换字符类型
 header('Content-Type: text/html; charset=big5'); // 繁体文件头
 return $str;
}
if(session_is_registered("php2000_big5") && ($php2000_big5==1)){ // 判断标志
 $fp = fopen('big5.table', 'r'); // big5的字库表
 $_gb_big5_ = fread($fp, filesize('big5.table')); // 读出数据
 fclose($fp);
 ob_start('translate_gb2big5'); // 启动输出信息控制
}
?>


  3、使用方法,这里给出一个最简单的例子,放在和 require.php 同一个目录里面

  test.php

<?
require("require.php");
echo "大家好,这里是 PHP 世纪网";
?>
<a href=php2000_gb_big5.php>
<?
if($php2000_big5==1)echo "GB";
else echo "Big5";
?>
</a>


  第一次运行结果为默认简体如下:

大家好,这里是 PHP 世纪网 Big5

  点击 Big5 连接显示繁体如下

大家好,這里是 PHP 世紀網 GB

  点击 GB 将返回简体页面

  由于使用了session 保存了简繁体标志,这样其他任何使用了 require.php 的页面都会自动按照当前的标志显示相应的页面。更多的实例请看我的网站 http://www.php2000.com 。

  4、big5 字库的保存的改进方法

  曾经考虑使用 session 来保存 big5 字库,但使用后发现速度明显减慢,主要因为 session 也是通过文件形式实现,所以不会对性能产生提高,而且因为session 不会根据简繁体标志自动判断装载与否,所以造成在简体下也装载了 big5 的字库,所以造成速度减慢。

  由于我用的服务器为 linux 所以考虑使用共享内存(Windows 不支持共享内存)来保存 big5 字库信息。其更改的代码为require.php 的判断部分:

<?
if(session_is_registered("php2000_big5") && ($php2000_big5==1))
{
 // 修改成使用共享内存
 // 判断是否已经创建,打开50000字节的 0xff3 段的共享内存
 $shm_id = @shmop_open(0xff3, "a", 0644, 50000);
 if($shm_id) {
  $_gb_big5_ = shmop_read($shm_id, 0,shmop_size($shm_id)); // 读出big5 数据
 }
 else{
  // 创建 50000 字节的系统标识为 0xff3 的共享内存块
  $shm_id = @shmop_open(0xff3, "c", 0644, 50000);

  // 读出数据
  $fp = fopen('big5.table', 'r');
  $_gb_big5_ = fread($fp, filesize('big5.table'));
  fclose($fp);

  if($shm_id){
   $shm_bytes_written = shmop_write($shm_id, $_gb_big5_,0); // 写入 big5 数据
  }
 }
 ob_start('translate_gb2big5');
}
?>


  关于共享内存的使用方法,请参看有关资料。

  四 结论

  PHP 作为一种公开源代码的脚本语言,其扩充性是非常好的。本文只是对其一个功能的一种应用方式的探讨,并实现了比较完美的同一页面自动简繁体转换功能。希望广大爱好 php 的朋友能从中得到启发,做出更好的作品。



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

See all articles