<?php
$f = fopen("test.txt", "wb"); // 二進位模式避免換行轉換
$text = utf8_encode("測試內容"); // 將 ISO-8859-1 字串轉 UTF-8 (若原已是 UTF-8 可省略)
$text = "\xEF\xBB\xBF" . $text; // 前置 UTF-8 BOM (EF BB BF)
fwrite($f, $text);
fclose($f);
?>
wb 模式:Windows 下防止 \n 自動轉 \r\n,確保位元組精確寫入。utf8_encode():僅適用 ISO-8859-1 → UTF-8。若來源已是 UTF-8 字串,直接使用原字串。EF BB BF):讓 Notepad 等編輯器自動辨識 UTF-8;XML/JSON 標準不建議加 BOM,視用途決定。file_put_contents('test.txt', "\xEF\xBB\xBF" . $content); 更簡潔。以二進位模式寫入並手動前置 BOM,可產生帶簽章的 UTF-8 檔案,相容舊版 Windows 編輯器。新專案建議統一 UTF-8 無 BOM,搭配編輯器設定即可。