simplexml 错误处理 php

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1307275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 01:57:50  来源:igfitidea点击:

simplexml error handling php

phpxmlsimplexml

提问by mrpatg

I am using the following code:

我正在使用以下代码:

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:[email protected]/account/rate_limit_status.xml");
$left = $xml->{"remaining-hits"};
$total = $xml->{"hourly-limit"};
return $left."/".$total;
}

and getting these errors when the stream cannot connect:

并在流无法连接时收到这些错误:

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://[email protected]/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"

How can I handle these errors so I can display a user friendly message instead of what is shown above?

我该如何处理这些错误,以便显示用户友好的消息而不是上面显示的消息?

采纳答案by Briganti

I've found a nice example in the php documentation.

我在php 文档中找到了一个很好的例子。

So the code is:

所以代码是:

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;
    }
}

And the output, as we/I expected:

和输出,正如我们/我所期望的:

Failed loading 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

加载 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

回答by Alex

I thinks this is a better way

我认为这是一个更好的方法

$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);

more info: http://php.net/manual/en/function.libxml-use-internal-errors.php

更多信息:http: //php.net/manual/en/function.libxml-use-internal-errors.php

回答by Mārti?? Briedis

If you look at the manual, there is an options parameter:

如果您查看手册,则有一个 options 参数:

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

Options list is available: http://www.php.net/manual/en/libxml.constants.php

选项列表可用:http: //www.php.net/manual/en/libxml.constants.php

This is the correct way to suppress warnings parsing warnings:

这是抑制警告解析警告的正确方法:

$xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);

回答by Halfstop

This is an old question, but is still relevant today.

这是一个古老的问题,但今天仍然相关。

The correct way to handle exceptions when using the oop SimpleXMLElment is like so.

使用 oop SimpleXMLElment 时处理异常的正确方法是这样的。

libxml_use_internal_errors(TRUE); // this turns off spitting errors on your screen
try {
  $xml = new SimpleXMLElement($xmlStringOfData);
} catch (Exception $e) {
  // Do something with the exception, or ignore it.
}

回答by Robert G.

My little code:

我的小代码:

try {
    libxml_use_internal_errors(TRUE);
    $xml = new SimpleXMLElement($xmlString);
    echo '<pre>'.htmlspecialchars($xml->asXML()).'</pre>';
} catch (Exception $e) {
    echo 'Caught exception: ' . $e->getMessage() . chr(10);
    echo 'Failed loading XML: ' . chr(10);
    foreach(libxml_get_errors() as $error) {
        echo '- ' . $error->message;
    }
}

Result example:

结果示例:

Caught exception: String could not be parsed as XML
Failed loading XML: 
- Opening and ending tag mismatch: Body line 3 and Bod-y

回答by Ignas R

The documentation says that in the case of an error, simplexml_load_file returns FALSE. So, you can use the "shut-up" operator (@) in combination with a conditional statement:

文档说,在出现错误的情况下, simplexml_load_file 返回 FALSE。因此,您可以将“关闭”运算符 (@) 与条件语句结合使用:

if (@simplexml_load_file($file))
{
    // continue
}
else 
{
    echo 'Error!';
}

回答by mere-teresa

if (simplexml_load_file($file) !== false) { // continue } else { echo 'Error!'; }

if (simplexml_load_file($file) !== false) { // 继续 } else { echo 'Error!'; }

And Twitter is down, maybe ?

Twitter的宕机,也许?