0

I am looking to handle a situation whereby the XML file that I at trying to retrieve is not ready or is not available.

I am using:

 $object = simplexml_load_string($file);

Sometimes, I get the following error:

'Start tag expected, '<' not found in etc...'

I have tried the following, and it doesn't work.

 if($object === false){
 // code here
}

1 Answer 1

1

simplexml_load_string can return false if there is an error. It can also emit a warning.

From the manual:

Returns an object of class SimpleXMLElement with properties containing the data held within the xml document, or FALSE on failure.

Produces an E_WARNING error message for each error found in the XML data.

Use libxml_use_internal_errors() to suppress all XML errors, and libxml_get_errors() to iterate over them afterwards.

// suppress warnings so we can handle them ourselves
libxml_use_internal_errors(true);

$object = simplexml_load_string($file);

if ($object === false) {
    // oh no
    $errors = libxml_get_errors();
    // do something with them
    print_r($errors);
    // really you'll want to loop over them and handle them as necessary for your needs
}

More detail on libxml_get_errors here.

Sign up to request clarification or add additional context in comments.

2 Comments

Implementing what you suggested I nevertheless get 'Warning: simplexml_load_string(): Entity: line 1: parser error : Start tag expected, '<' not found in....' - is this something i need to turn off in the php.innit file?
My bad, it needs to be passed with true as an option! Feels like the default should be true rather than false, considering the name "use internal errors".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.