Question

I want to replace the list of warnings and errors with a simple error banner. I'm trying to check if this code produce errors and if so output a custom error

$sxml = simplexml_load_file($yurl)

I played around with the try catch block but I just can't seem to get it right, any help will be appreciated.

Was it helpful?

Solution

Use libxml_use_internal_errors()

<?php

    libxml_use_internal_errors(true);

    $sxml = simplexml_load_file($yurl);

    if (!$sxml) {
        foreach (libxml_get_errors() as $error) {
            // Custom error banner here
                switch ($error->level) {
                    case LIBXML_ERR_WARNING:
                        $return .= "Warning $error->code: ";
                        break;
                    case LIBXML_ERR_ERROR:
                        $return .= "Error $error->code: ";
                        break;
                    case LIBXML_ERR_FATAL:
                        $return .= "Fatal Error $error->code: ";
                        break;
                    }    
        }
            //clears libxml error buffer
        libxml_clear_errors();
    }

?>

libxml_get_errors() returns an array of libXMLError objects.

OTHER TIPS

You can only catch exceptions, not errors.

Use set_error_handler() to replace PHP's default error handler with your own function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top