【问题标题】:simplexml error handling phpsimplexml 错误处理 php
【发布时间】:2017-02-28 16:31:57
【问题描述】:

我正在使用以下代码:

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"

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

【问题讨论】:

  • 考虑更改所选答案?问题是“我该如何处理这些错误?”选择的答案只是告诉你如何避免不得不这样做。
  • @TimOgilvy 完成,谢谢。

标签: php xml simplexml


【解决方案1】:

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

$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

【讨论】:

  • 只有一个回答了这个问题。与libxml_get_errors()libxml_get_last_error() 一起使用以获取错误消息。
  • 但是,这无法获取 simplexml_load_file 转储的所有警告消息。
  • 我试过了,但收到一条警告消息,所以我只是做了 $xml = @simplexml_load_file($url);并且没有警告并按预期处理错误
【解决方案2】:

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

所以代码是:

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

【讨论】:

  • 但是,这无法获取 simplexml_load_string 转储的所有警告消息。
【解决方案3】:

如果你看手册,有一个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);

【讨论】:

  • 对我不起作用,仍然在 PHP 5.4.x 中生成了 E_WARNING
  • 这个答案是一个简单有效的解决方案,让我头疼!注意那些可能有错误的人:如果您有多个 LIBXML_XXXX,请务必使用管道分隔,如 LIBXML_NOCDATA | LIBXML_COMPACT | LIBXML_NOWARNING
【解决方案4】:

这是一个老问题,但今天仍然适用。

使用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.
}

【讨论】:

    【解决方案5】:

    我的小代码:

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

    结果示例:

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

    【讨论】:

      【解决方案6】:

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

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

      【讨论】:

      • 请不要闭嘴,不要闭嘴!
      • 这样的?函数 GetTwitterAvatar($username){ if(@simplexml_load_file("twitter.com/users/".$username.".xml")){ $xml = simplexml_load_file("twitter.com/users/".$username.".xml"); $imgurl = $xml->profile_image_url;返回 $imgurl; } 其他 { 返回“错误”; } }
      • 你可以不调用 simplexml_load_file 两次: $xml = @simplexml_load_file("..."); if ($xml) { ... } else { return 'Error'; }
      • mere-teresa,但他需要在此处抑制警告...当然,您也可以使用 display_errors 设置或将错误转换为异常然后使用 try/catch,但这要简单得多...
      • @IgnasR 你可以做得更简单: if (!$xml = simplexml_load_file($file)) { echo 'Error!';返回假; } else { //你的代码 }
      猜你喜欢
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 2023-03-04
      • 2015-07-05
      相关资源
      最近更新 更多