2010-04-10 100 views
0

我想爲我創建的應用程序使用Last.fm API,但在驗證時遇到了一些問題。DOMDocument加載頁面返回400錯誤請求狀態

如果API請求給它返回該例在響應XML代碼和信息的錯誤:

<lfm status="failed"> 
<error code="6">No user with that name</error> 
</lfm> 

然而,該請求還返回400(或在一些情況下403)的HTTP狀態,其DOMDocument考慮錯誤,因此拒絕解析XML。

有沒有辦法繞過這個,以便我可以檢索錯誤代碼和消息?

感謝

皮特

回答

1

一個解決方案可以分兩步分開你的操作:

  • 首先,獲取XML字符串,使用curl,例如
  • 然後,該字符串與DOMDocument工作。


有一個如何可以在curl_exec手冊頁上使用捲曲的例子。增加了一些有用的選項,你可以使用這樣的事情,我想:

$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "YUR_URL_HERE"); 
curl_setopt($ch, CURLOPT_HEADER, false); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$xml_string = curl_exec($ch); 
curl_close($ch); 

// You can now work with $xml_string 

而且,對於更多的選擇(也有很多他們的^^),你可以看看它的用戶手冊curl_setopt

+0

完成了它 - 謝謝! – 2010-04-11 19:12:38

0

你隨時都可以與像file_get_contents一些其他功能的反應,然後用DOMDocument::loadXML

編輯解析XML:

http://www.php.net/manual/en/domdocument.load.php#91384

+0

這是我的第一個想法太多,但可悲的是它給了相同的結果: 警告:的file_get_contents(someurl.com)function.file-GET-內容]:未能打開流:HTTP請求失敗!第23行的userclass.php中的HTTP/1.0 400錯誤請求 – 2010-04-11 19:05:15

0

的功能:

function getAlbum($xml,$artist,$album) 
{ 
    $base_url = $xml; 
    $options = array_merge(array(
    'user' => 'YOUR_USERNAME', 
    'artist'=>$artist, 
    'album'=>$album, 
    'period' => NULL, 
    'api_key' => 'xYxOxUxRxxAxPxIxxKxExYxx', 
)); 

    $options['method'] = 'album.getinfo'; 

    // Initialize cURL request and set parameters 
    $ch = curl_init($base_url); 
    curl_setopt_array($ch, array(
    CURLOPT_URL   => 'http://ws.audioscrobbler.com/2.0/', 
    CURLOPT_POST   => TRUE, 
    CURLOPT_POSTFIELDS  => $options, 
    CURLOPT_RETURNTRANSFER => TRUE, 
    CURLOPT_TIMEOUT  => 30, 
    CURLOPT_HTTPHEADER  => array('Expect:') , 
    CURLOPT_USERAGENT  => 'Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)' 
)); 

    $results = curl_exec($ch); 
    unset ($options); 
    return $results; 
} 

用法:

// Get the XML 
$xml_error = getAlbum($xml,$artist,$album); 

// Show XML error 
if (preg_match("/error/i", $xml_error)) { 
    echo " <strong>ERRO:</strong> ".trim(strip_tags($xml_error)); 
} 
1

我用盡量&抓解決了這個問題。如果它可以幫助別人

function getXML($xml) { 
      $dom = new DomDocument(); 
     try { 
      @$dom->load($xml); // The '@' is necessary to hide error if it's a error 400 - Bad Request 
      $root = $dom->documentElement; 
      return $root; 
     } 
     catch(Exception $e) 
     { 
      return false; 
     } 
    } 
相關問題