Ben
Ben

Reputation: 62336

SimpleXML throwing warnings - how to catch?

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
                }

Upvotes: 3

Views: 9799

Answers (3)

fitorec
fitorec

Reputation: 4765

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!

Upvotes: 1

Roman Losev
Roman Losev

Reputation: 1941

In my situation server which was sharing XML changed their http to https. Because of that we were downloading old path XML file, which in this case was "corrupted". That is why we had the error.

XML files was loading perfectly because of that i didn't noticed https problem ( browser redirect ).

Upvotes: 0

Hemaulo
Hemaulo

Reputation: 999

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

Upvotes: 17

Related Questions