2

Possible Duplicate:
PHP Catching a SimpleXMLElement parse error

I am using xml file for file upload. I have use simplexml_load_file("files/sample.xml"); If given xml file error means, it will show warning like this,

Warning (2): simplexml_load_file() [http://php.net/function.simplexml-load-file]: files/sample.xml:8: parser error : Opening and ending tag mismatch:
Warning (2): simplexml_load_file() [http://php.net/function.simplexml-load-file]:

I have get warning using try catch. I am using cakePHP

Community
  • 1
  • 1
Sundar
  • 159
  • 1
  • 9
  • Isn't it obvious that this depends on the input file? Show it! Unless the question isn't about the warning. – AndreKR Oct 17 '12 at 09:04
  • Here i am using, try{ $xml = simplexml_load_file("files/sample.xml"); } catch (Exception $e){ //$this->set('err_msg',"Invalid XML file"); echo "Invalid"; exit; } – Sundar Oct 17 '12 at 09:05
  • 1
    That are warnings, not exceptions. You can not "catch" them with a `try {} catch {}` block. – hakre Oct 17 '12 at 09:06
  • If given xml is wrong show error message to user. – Sundar Oct 17 '12 at 09:07
  • Then get them: http://www.php.net/manual/en/function.libxml-get-errors.php – hakre Oct 17 '12 at 09:09

2 Answers2

1

Your script is loading the file. However, the file cannot be parsed as XML.

To stop warnings being automatically spit out onto the page (it'll do this regardless of whether or not you try/catch), you'll need to use:

libxml_use_internal_errors(true);

Before dealing with any class that uses libxml.

Description from PHP.net:

libxml_use_internal_errors — allows you to disable standard libxml errors and enable user error handling.

Wayne Whitty
  • 19,513
  • 7
  • 44
  • 66
1

If you want to try/catch a warning, you have to 'convert' the warning into a exception.

Set your global error handle like this:

set_error_handler( 'error_handler' );

and then convert the warning to a exception:

function error_handler( $errno, $errmsg, $filename, $linenum, $vars )
  {
    // error was suppressed with the @-operator
    if ( 0 === error_reporting() )
      return false;

    if ( $errno !== E_ERROR )
      throw new \ErrorException( sprintf('%s: %s', $errno, $errmsg ), 0, $errno, $filename, $linenum );

}
JvdBerg
  • 21,777
  • 8
  • 38
  • 55