2010-12-17 107 views
2

我無法使用simplexml_load_file函數從文件獲取XML。我曾嘗試使用Google,但其他人似乎在遇到實際錯誤或警告時遇到問題。我沒有得到任何錯誤,沒有警告,但是當我這樣做:PHP - 使用simplexml_load_file獲取XML的問題

$sims = simplexml_load_file("http://my-url.com/xml.php") or die("Unable to load XML file!"); 
var_dump($sims); 

輸出爲:

object(SimpleXMLElement)#1 (1) { 
    [0]=> 
    string(1) " 
" 
} 



但是,如果我這樣做:

$ch = curl_init("http://my-url.com/xml.php"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch); 
echo $output; 

輸出是:

<?xml version="1.0"?> 
<simulators> 
    <simulator> 
     <mac>00-1A-4D-93-27-EC</mac> 
     <friendlyName>a Travis Desk</friendlyName> 
     <roundSessions>2</roundSessions> 
     <rangeSessions>0</rangeSessions> 
     <timePlayed>00:03:21</timePlayed> 
    </simulator> 
</simulators> 



我得到它做這個工作:

$ch = curl_init("http://my-url.com/xml.php"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
curl_close($ch); 

$sims = simplexml_load_string($output) or die("Unable to load XML file!"); 
var_dump($sims); 

,輸出:

object(SimpleXMLElement)#1 (1) { 
    ["simulator"]=> 
    object(SimpleXMLElement)#2 (5) { 
    ["mac"]=> 
    string(17) "00-1A-4D-93-27-EC" 
    ["friendlyName"]=> 
    string(13) "a Travis Desk" 
    ["roundSessions"]=> 
    string(1) "2" 
    ["rangeSessions"]=> 
    string(1) "0" 
    ["timePlayed"]=> 
    string(8) "00:03:21" 
    } 
} 

我只是想知道爲什麼第一個方法不起作用?我有在Ubuntu Server 10.04上運行的PHP Version 5.3.2-1ubuntu4.5和libxml版本2.7.6。

謝謝!

-Travis

+0

可以確認URL僅僅是通過'http:// my-url.com/xml.php'沒有任何'$ _GET'? – ajreal 2010-12-17 16:56:11

回答

-1

感謝您的快速反應。

@ajreal - 你是在正確的軌道上。原來,這是我自己在查詢字符串中的一個愚蠢的錯誤,出於某種原因,它通過cURL或瀏覽器調用它時起作用,但通過simplexml_load_file無法工作。對不起浪費你的時間!

-Travis

1

我相信這可能是因爲您的XML內容位於PHP擴展文件中。您需要將http標頭設置爲xml。

header ("Content-type: text/xml"); 

把這個xml輸出到你的php腳本中,它是負責吐出xml的。 (一在 「http://my-url.com/xml.php」)

http://www.satya-weblog.com/2008/02/header-for-xml-content-in-php-file.html

+0

很好的建議,但事實證明它不是必需的。可能是一個好主意,但我認爲simplexml_load_file函數只是將URL的輸出作爲一個字符串來使用,所以我認爲在開始時就需要<?xml version =「1.0」?>「。不過謝謝你的迴應! – Travesty3 2010-12-17 17:15:56