PHP 腳本從資料庫讀取資料並輸出 XML 格式字串,但瀏覽器直接顯示原始碼而非結構化 XML 樹狀視圖。
在任何輸出之前發送正確的 HTTP 標頭:
<?php
header("Content-Type: text/xml; charset=utf-8");
// 或
header("Content-Type: application/xml; charset=utf-8");
// 後續輸出 XML 內容
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<data><item>火影</item></data>';
?>
header() 前不能有任何輸出(含 BOM),否則會觸發「Cannot modify header information」警告。short_open_tag=On,<?xml 會被誤判為 PHP 標籤,解決:echo '<?xml ...'; 或關閉短標籤。header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // 過去時間
// 確保即時資料不被快取
只要在輸出 XML 前正確呼叫 header("Content-Type: text/xml"),瀏覽器即會啟用內建 XML 解析器呈現結構化視圖。注意標頭輸出順序與編碼一致性,即可穩定產出合法 XML 回應。