simplexml error handling php

前端 未结 7 1273
失恋的感觉
失恋的感觉 2020-11-27 19:50

I am using the following code:

function GetTwitterAvatar($username){
$xml = simplexml_load_file(\"http://twitter.com/users/\".$username.\".xml\");
$imgurl =          


        
相关标签:
7条回答
  • 2020-11-27 20:31

    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

    0 讨论(0)
  • 2020-11-27 20:38

    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:

    if (@simplexml_load_file($file))
    {
        // continue
    }
    else 
    {
        echo 'Error!';
    }
    
    0 讨论(0)
  • 2020-11-27 20:39

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

    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
    
    0 讨论(0)
  • 2020-11-27 20:40

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

    And Twitter is down, maybe ?

    0 讨论(0)
  • 2020-11-27 20:42

    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
    
    0 讨论(0)
  • 2020-11-27 20:50

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

    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

    This is the correct way to suppress warnings parsing warnings:

    $xml = simplexml_load_file('file.xml', 'SimpleXMLElement', LIBXML_NOWARNING);
    
    0 讨论(0)
提交回复
热议问题