28

私は次のコードを使用しています:

function GetTwitterAvatar($username){
$xml = simplexml_load_file("http://twitter.com/users/".$username.".xml");
$imgurl = $xml->profile_image_url;
return $imgurl;
}

function GetTwitterAPILimit($username, $password){
$xml = simplexml_load_file("http://$username:$password@twitter.com/account/rate_limit_status.xml");
$left = $xml->{"remaining-hits"};
$total = $xml->{"hourly-limit"};
return $left."/".$total;
}

ストリームが接続できないときにこれらのエラーが発生します。

Warning: simplexml_load_file(http://twitter.com/users/****.xml) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://twitter.com/users/****.xml" 

Warning: simplexml_load_file(http://...@twitter.com/account/rate_limit_status.xml) [function.simplexml-load-file]: failed to open stream: HTTP request failed! HTTP/1.0 503 Service Unavailable

Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "http://***:***@twitter.com/account/rate_limit_status.xml"

上記の代わりにユーザーフレンドリーなメッセージを表示できるように、これらのエラーをどのように処理できますか?

4

6 に答える 6

48

私はこれがより良い方法だと思います

$use_errors = libxml_use_internal_errors(true);
$xml = simplexml_load_file($url);
if (false === $xml) {
  // throw new Exception("Cannot load xml source.\n");
}
libxml_clear_errors();
libxml_use_internal_errors($use_errors);

詳細: http://php.net/manual/en/function.libxml-use-internal-errors.php

于 2011-01-03T08:59:34.323 に答える
26

PHPのドキュメントで素敵な例を見つけました。

したがって、コードは次のとおりです。

libxml_use_internal_errors(true);
$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");
if (false === $sxe) {
    echo "Failed loading XML\n";
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}

そして、私たち/私が予想したように、出力は次のとおりです。

XML の読み込みに失敗しました

Blank needed here
parsing XML declaration: '?>' expected
Opening and ending tag mismatch: xml line 1 and broken
Premature end of data in tag broken line 1
于 2011-12-14T09:01:20.403 に答える
9

マニュアルを見ると、 options パラメータがあります。

SimpleXMLElement simplexml_load_file ( string $filename [, string $class_name = "SimpleXMLElement" [, int $options = 0 [, string $ns = "" [, bool $is_prefix = false ]]]] )

オプションのリストが利用可能です: http://www.php.net/manual/en/libxml.constants.php

これは、警告を解析する警告を抑制する正しい方法です。

$xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);
于 2013-04-17T05:17:15.377 に答える
-1

ドキュメントによると、エラーが発生した場合、simplexml_load_fileはFALSEを返します。したがって、「シャットダウン」演算子(@)を条件ステートメントと組み合わせて使用​​できます。

if (@simplexml_load_file($file))
{
    // continue
}
else 
{
    echo 'Error!';
}
于 2009-08-20T16:16:31.333 に答える