Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleXML throwing warnings - how to catch?

Tags:

php

xml

simplexml

I'm having some trouble determining what's going on with simplexml_load_string() I'm using the below code to render some XML.... when I run this code I get error messages like:

Message: simplexml_load_string() [function.simplexml-load-string]: Entity: line 94: parser error : Opening and ending tag mismatch: meta line 15 and head

Any ideas on how I can catch these warnings? libxml_get_errors has no affect.

                $response = simplexml_load_string($response);
                var_dump($response);
                if (count(libxml_get_errors()) > 0) {
                    print_r(libxml_get_errors());
                }

                if (is_object($response)) { //returns true when warnings are thrown
                    //process response
                } else {
                    //record error
                }
like image 637
Webnet Avatar asked Dec 06 '25 06:12

Webnet


2 Answers

libxml_use_internal_errors(true); // !!!

$elem = simplexml_load_string($xml);
if($elem !== false)
{
    // Process XML structure here
}
else
{
    foreach(libxml_get_errors() as $error)
    {
        error_log('Error parsing XML file ' . $file . ': ' . $error->message);
    }
}
like image 186
Hemaulo Avatar answered Dec 08 '25 16:12

Hemaulo


Other solution, in PHP you can ignore any error messages usign the error control operator(@), in this case:

$data = @simplexml_load_string($xml);
if ($data === false) { // catch error!
    foreach(libxml_get_errors() as $error) {
        echo "\t", $error->message;
    }
}

Check this doc: http://php.net/manual/en/language.operators.errorcontrol.php

Good luck!

like image 25
fitorec Avatar answered Dec 08 '25 17:12

fitorec