0

我正在尝试将 Last.fm API 用于我正在创建的应用程序,但在验证时遇到了一些问题。

如果 API 请求出错,它会在响应 XML 中返回代码和消息,如下所示:

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

但是,该请求还返回 400(或在某些情况下为 403)的 HTTP 状态,DOMDocument 认为这是一个错误,因此拒绝解析 XML。

有什么办法可以解决这个问题,以便我可以检索错误代码和消息?

谢谢

皮特

4

4 回答 4

1

一个解决方案可能是将您的操作分为两个步骤:

  • 首先,使用curl获取 XML 字符串,例如
  • 然后,使用DOMDocument.


curl_exec手册页 上有一个如何使用 curl 的示例;添加一些有用的选项,你可以使用这样的东西,我想:

$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.

于 2010-04-11T12:38:14.940 回答
1

我通过使用 try & catch 解决了这个问题。如果它可以帮助某人

    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;
        }
    }
于 2011-12-22T10:08:27.303 回答
0

您始终可以使用其他一些函数获取响应,file_get_contents然后使用DOMDocument::loadXML

编辑:

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

于 2010-04-10T23:04:23.873 回答
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));
}
于 2011-05-05T16:53:29.207 回答