Developing software in the Real World

Throw an exception when simplexml_load_string fails

I keep having to look up how to stop the warning that are emitted when simplexml_load_string & simplexml_load_file fail, so this time I’ve written the world’s simplest little class to take care of it for me from now on:

Update: The code has been updated based on the comments below. Thanks!

4 thoughts on “Throw an exception when simplexml_load_string fails

  1. Thanks for the code! I think it makes a lot of sense to use exceptions.

    There are two things I would like to suggest:

    * Use a more detailed exception: either "UnexpectedValueException", or maybe your custom XMLException (based on RunTimeException). This allows for an even more fine-grained exception catching (even though nothing else will throw an exception in the code, we shouldn't assume)

    * save the result from initial libxml_use_internal_errors() and restore this instead of returning it to false. There is no guarantee that this value was false to begin with, and in that case, this function will change external behaviour.

  2. Also, it's probably a good idea to restore the libxml_use_internal_errors even if the call fails, otherwise the function will again change external behavior on errors.

  3. Nice, I didn't know libxml_use_internal_errors suppresses the PHP warning. If you are using PHP 5.5+, the code can be further improved by adding a try/finally block so the libxml_use_internal_errors() value is also restored in case an exception is thrown.


Comments are closed.