我在读取数据(使用特殊字符)到文件时遇到问题。PHP:读取和写入数据(带有特殊字符)到文件的问题
我做这样的事情:
//Writing data..
<?php
header('Content-Type: text/html; charset=utf-8');
$file = 'filename.db';
$data = 'Some string with special characters';
//Writing to the file..
@file_put_contents($file, json_encode($data));
?>
这工作得很好。 当我在Notepad ++中打开db文件时,数据是正确的。 特殊字符也存储正确:
//Reading data..
<?php
header('Content-Type: text/html; charset=utf-8');
$file = 'filename.db';
//Reading from the file..
$data = file_get_contents($file);
$data = json_decode(utf8_encode(stripslashes($data)));
echo $data;
?>
这显示特殊字符为“????”或有时像“u00cf”或其他字符。
什么问题出在哪里?
任何帮助,将不胜感激, 谢谢。
为什么'utf8_encode'? –
在UTF-8中,值为0xcf的字节是“连续字节”,即多字节序列的尾部的一部分,这表明UTF-8在某些时候不被解释为这样。如果你能提供确切的字符串和文件的确切内容,这将有所帮助,因为“特殊字符”对你来说意味着与我们其他人不同的东西。最后,你的PHP源文件的编码是什么? PHP将字符串视为字节,因此它不关心它是UTF-8还是Latin-1,但像utf8_encode()这样的东西只在预期的输入匹配时才做正确的事情。 –
只需停止不必要地使用stripslashes和utf8_encode搞乱你的数据。 – deceze