UTF-8不适用于PHP ob_get_clean/include_once+;什么事?
我想这和我的问题很相似,但是这个答案对我没有帮助,所以我举了一个简单的“有效”的例子来说明我的问题。此测试中有三个文件:UTF-8不适用于PHP ob_get_clean/include_once+;什么事?,php,utf-8,Php,Utf 8,我想这和我的问题很相似,但是这个答案对我没有帮助,所以我举了一个简单的“有效”的例子来说明我的问题。此测试中有三个文件: utftest.txt øæå jeść ясть <?php echo htmlentities( $content ); ?> <?php echo 'Current PHP version: ' . phpversion() . "\r\n\r\n"; $content = file_get_contents("utftest.txt"
utftest.txt
øæå jeść ясть
<?php echo htmlentities( $content ); ?>
<?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);
?>
utftempl.txt
øæå jeść ясть
<?php echo htmlentities( $content ); ?>
<?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
我使用phpcli
解释器和phputfest.php
运行这个测试。在我的本地PC上,我在终端中获得以下输出:
$ php utftest.php
Current PHP version: 5.5.9-1ubuntu4.14
øæå jeść ясть
。。。这正是我所期望的。但是,当我将其上传到远程服务器,并通过ssh
登录到远程服务器,并在终端中执行相同的测试时,我得到以下结果:
$ php utftest.php
Current PHP version: 5.3.10-1ubuntu3.21
øæå jeÅ�Ä� ÑNtilde;�Ñ�Ñ�
所以,出于某种原因,在服务器上,我得到了更多的HTML实体,加上一些二进制字符
为什么会发生这种情况?是因为不同的PHP版本吗?我怎样才能让这个测试脚本即使在服务器上也能正确运行呢 好吧,我想我找到了答案: htmlentities()接受可选的第三个参数编码,该参数定义转换中使用的编码。在PHP5.6.0中,默认字符集值用作默认值。在PHP5.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");
?>