錯誤訊息 Invalid byte 1 of 1-byte UTF-8 sequence 表示 XML 宣告為 UTF-8,但實際內容含非 UTF-8 位元組(常見為 GBK/Big5 編碼的中文)。Windows 環境下 Java 預設編碼為 GBK,即便程式碼指定 UTF-8,檔案實際可能以 GBK 寫入。
<?php
// 檢查檔案實際編碼
$content = file_get_contents('data.xml');
var_dump(mb_detect_encoding($content, ['UTF-8', 'GBK', 'BIG5']));
// 若輸出 GBK,即為編碼不匹配
<?xml version="1.0" encoding="gbk"?>
若來源檔案確實為 GBK,直接改宣告即可,PHP simplexml_load_file 會自動轉換。
使用編輯器(VS Code、Notepad++)開啟檔案,另存為 UTF-8 編碼。或程式化轉換:
<?php
$content = file_get_contents('data.xml');
$content = iconv('GBK', 'UTF-8//IGNORE', $content);
file_put_contents('data_utf8.xml', $content);
// 再解析 data_utf8.xml
<?php
$xml = simplexml_load_file('data.xml', 'SimpleXMLElement', LIBXML_NOERROR, 'GBK');
// 或 DOMDocument
$dom = new DOMDocument();
$dom->load('data.xml', LIBXML_NOERROR); // 需配合 encoding 宣告
原因:XML 宣告前有空白字元(BOM、空行、空格)。解決:
<?php
$content = file_get_contents('data.xml');
$content = trim($content); // 移除首尾空白
$xml = simplexml_load_string($content);
header('Content-Type: application/xml; charset=UTF-8')DOMDocument 而非 SimpleXML,支援更完整的編碼處理與錯誤回報libxml_use_internal_errors(true) 捕捉詳細錯誤