2014-12-06 159 views
-1

我一直在用simplexml_load_file獲取XML內容,任何想法爲什麼它不起作用? ?是否有事情做與下面的源..爲什麼我的simplexml_load_file不起作用?

$Url='http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS'; 
$XML=simplexml_load_file($Url); 
+1

這不是一個文件。這是一個URL。 – 2014-12-06 16:17:21

+0

你說得對,我認爲這將是與URL的東西,但這個網址是生成XML輸出,不是嗎?你能給我建議如何得到結果嗎? – 2014-12-06 16:34:17

+0

@MichalSlesingr:請啓用PHP錯誤報告和日誌記錄。然後看看實際的錯誤消息。另請參見:[如何在PHP中獲取有用的錯誤消息?](http://stackoverflow.com/q/845021/367456) – hakre 2014-12-22 11:40:55

回答

0

對於FOM原因,如果你打開這個鏈接在瀏覽器,它的XML。如果你試圖讓我通過PHP這是JSON。 試試這個代碼

$Url='http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS'; 

$fileContent = json_decode(file_get_contents($Url)); 
+0

是的,我發現一樣,反正謝謝...;) – 2014-12-07 17:12:54

0

你應該使用:

$Url='http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS'; 
$XML=simplexml_load_file(file_get_contents($Url)); 
+0

這並沒有解決問題,仍然沒有工作......我也試過file_get_contents然後simplexml_load_string,用盡想法...:/ – 2014-12-06 16:31:00

+0

而且你也不應該使用它。在一定程度上,file_get_contents以及simplexml_load_file使用完全相同的例程。接下來,答案中給出的代碼顯然是錯誤的,它可能意味着使用simplexml_load_string而不是simplexml_load_file。 -1。 – hakre 2014-12-22 11:34:52

0

發現原來的file_get_contents返回JSON這樣:

$ X = json_decode(的file_get_contents( $ URL));

的伎倆......

0

有你的代碼,以防止你找出什麼很快會在這裏對你自己(以及如何找到一個解決方案)兩個小的(但常見的)錯誤。

首先,你沒有做任何錯誤檢查。如果無法打開文件,simplexml_load_file()將返回FALSE

$xml = simplexml_load_file($url); 
if (!$xml) { 
    // error opening the URL 
    return false; 
} 

這還不是非常豐富的,你可以現在只是讓PHP錯誤報告/日誌真正看到其產生的誤差:

警告:使用simplexml_load_file():HTTP // :數據中心。 biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS:1:分析器錯誤:開始標記預期, '<' 中找不到[...]

警告:使用simplexml_load_file():{ 「ASOF」 : 「2014-12-22T11:45:50.5976703 + 00:00」, 「RaceCount」:25, 「行」:[{ 「等級」:」 1" ,」 [...]

警告:使用simplexml_load_file()^在[...]

這已經預示着HTTP請求到該URL不提供XML,但是JSON(看到第二個警告)。

這是很容易通過告訴服務器接受此XML驗證:

stream_context_set_default(['http' => ['header' => "Accept: text/xml"]]); 
$xml = simplexml_load_file($url); 

whcih現在只是工作,現在服務器提供XML可以通過正確解析和的SimpleXMLElement創建。

的完整代碼例如:

<?php 

$url = 'http://datacenter.biathlonresults.com/modules/sportapi/api/CupResults?CupId=BT1415SWRLCP__SMTS'; 
stream_context_set_default(['http' => ['header' => "Accept: text/xml"]]); 
$xml = simplexml_load_file($url); 
if (!$xml) { 
    // error opening the file 
    var_dump(libxml_get_errors()); 
    return false; 
} 

$xml->asXML('php://output'); 

輸出:

<?xml version="1.0"?> 
<CupResultsResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/sportapi"><AsOf>2014-12-22T11:45:50.5976703+00:00</AsOf><RaceCount>25</RaceCount><Rows><CupResultRow>[...] 

此代碼示例的the answer of a very similar question一個較短的版本,其覆蓋相同的接地:

對於運行ASP.NET的Microsoft-IIS服務器,這種行爲似乎很典型,最有可能是一些REST API組件。