我在讀取數據(使用特殊字符)到文件時遇到問題。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