繁体   English   中英

UTF-8与PHP ob_get_clean / include_once + htmlentities不正确吗?

[英]UTF-8 incorrect with PHP ob_get_clean/include_once + htmlentities?

我猜这类似于在PHP中转换ob_get_clean结果 ,但是该答案对我没有帮助-因此,我为我的问题做了一个最小的“有效”示例。 此测试中包含三个文件:

utftest.txt

øæå jeść ясть

utftempl.txt

<?php echo htmlentities( $content ); ?>

utftest.php

<?php

  echo 'Current PHP version: ' . phpversion() . "\r\n\r\n";

  $content = file_get_contents("utftest.txt");
  $templateFile = "utftempl.txt";
  ob_start();
  include_once($templateFile);
  $file_output = ob_get_clean();
  print_r($file_output);

?>

我假设utftest.txt已正确编码为UTF-8,否则这里是hexdump:

$ hexdump -C utftest.txt 
00000000  c3 b8 c3 a6 c3 a5 20 6a  65 c5 9b c4 87 20 d1 8f  |...... je.... ..|
00000010  d1 81 d1 82 d1 8c 0a                              |.......|
00000017

我使用php-cli解释器和php utftest.php运行此测试。 在本地PC上,我在终端中获得以下输出:

$ php utftest.php
Current PHP version: 5.5.9-1ubuntu4.14

&oslash;&aelig;&aring; jeść ясть

...这就是我所期望的。 但是,当我将其上传到远程服务器并通过ssh登录到远程服务器并在终端中执行相同的测试时,我得到了:

$ php utftest.php 
Current PHP version: 5.3.10-1ubuntu3.21

&Atilde;&cedil;&Atilde;&brvbar;&Atilde;&yen; je&Aring;�&Auml;� &Ntilde;Ntilde;�&Ntilde;�&Ntilde;�

因此,由于某种原因,在服务器上,我得到了更多的HTML实体,以及一些二进制字符?

为什么会这样-是因为不同的PHP版本? 以及如何在服务器上正确运行此测试脚本?

好吧,我想我找到了答案:

htmlentities销毁utf-8字符串

htmlentities()采用可选的第三参数编码,该编码定义了转换中使用的编码。 从PHP 5.6.0起,default_charset值用作默认值。 从PHP 5.4.0开始,UTF-8是默认设置。 PHP 5.4.0之前的版本,默认使用ISO-8859-1。

因此,确实的问题是PHP版本。 所以解决方法是在utftempl.txt使用:

<?php //echo htmlentities( $content );
echo htmlentities( $content , ENT_QUOTES, "UTF-8");
?>

然后两个版本都可以正确执行所有操作...

这也是utftest.php的修改版本,带有更多调试输出:

<?php

  echo 'Current PHP version: ' . phpversion() . "\r\n\r\n";

  $content = file_get_contents("utftest.txt");
  print_r($content);
  echo "\r\nENC1: " . mb_detect_encoding($content) . "\r\n\r\n" ;
  $templateFile = "utftempl.txt";
  ob_start();
  include_once($templateFile);
  $file_output = ob_get_clean();
  print_r($file_output);
  echo "\r\nENC2: " . mb_detect_encoding($file_output) . "\r\n\r\n" ;
  echo htmlentities( "øæå jeść ясть" ) . "\r\n\r\n" ;
  echo htmlentities( "øæå jeść ясть", ENT_QUOTES, "UTF-8") . "\r\n\r\n" ;

?>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM