file_get_contents()
函數本身不會處理編碼問題,但你可以使用一些其他的 PHP 函數來解決編碼問題
file_get_contents()
讀取文件內容:$content = file_get_contents('your-file.txt');
mb_detect_encoding()
函數來實現這個目標:$current_encoding = mb_detect_encoding($content, 'auto');
iconv()
或 mb_convert_encoding()
函數進行轉換:使用 iconv()
:
$target_encoding = 'UTF-8';
$converted_content = iconv($current_encoding, $target_encoding.'//IGNORE', $content);
或者使用 mb_convert_encoding()
:
$target_encoding = 'UTF-8';
$converted_content = mb_convert_encoding($content, $target_encoding, $current_encoding);
$converted_content
變量包含已轉換為目標編碼的文件內容。你可以繼續處理這個內容,或者將其保存到文件中:file_put_contents('your-converted-file.txt', $converted_content);
這樣,你就可以使用 file_get_contents()
函數讀取文件內容,并通過轉換解決編碼問題。請注意,這里我們使用了 ‘//IGNORE’ 標志,它會忽略無法轉換的字符。你可以根據需要調整這個選項。