昨天有人反映一支有點年代的程式,載入 XML 時好時壞,畫面其他部分有產生出來,就是載入 XML 的部分不一定能順利產製。

查了一下,原本的寫法是:

<?php
$xml_file = "https://test/this.xml";
if (file_exists($xml_file)){
  $xml = simplexml_load_file($xml_file);
}
?>

感覺沒問題啊?寫法好正常普通。錯誤訊息長成這樣:

[Wed Dec 15 09:54:36.118236 2021] [proxy_fcgi:error]
AH01071: Got error 'PHP message: PHP Warning:  simplexml_load_file(): I/O warning : failed to load external entity "/htdocs/web/this.xml" in /htdocs/web/getxml.php on line 5
PHP message: PHP Fatal error:  Uncaught Error: Call to a member function xpath() on boolean in /htdocs/web/getxml.php:5
Stack trace:
#0 {main}
  thrown in /htdocs/web/getxml.php on line 5', referer: /htdocs/web/content.php

強者我前輩給我建議,叫我先透過 HTTP 取得內容後,再把取回的 HTTP response 轉成 XML string:

<?php $xml_file = "https://test/this.xml";
if (file_exists($xml_file)){
  // 先利用 file_get_contents() 取回內容
  // 再把取回的內容利用 simplexml_load_string() 轉為 XML

  $xml = simplexml_load_string(file_get_contents(xml_file));
}
?>

結果竟然就解決了。打完收工。

"SimpleXML - I/O warning : failed to load external entity" 這篇有提到,也有可能是因為 upload_max_filesizepost_max_size 這兩個值不夠大,造成 I/O 錯誤。

arrow
arrow
    文章標籤
    XML
    全站熱搜
    創作者介紹
    創作者 小攻城師 的頭像
    小攻城師

    小攻城師的戰場筆記

    小攻城師 發表在 痞客邦 留言(0) 人氣()