How to check for errors in an XML

Asked

Viewed 1,129 times

6

I’m using the function simplexml_load_string to load a dynamic XML, but if there are formatting errors in this XML it only returns me false and I don’t know where the bug is, is it possible for me to check this?

2 answers

5


You can create a simple function to check if XML is valid.

 <?php
function is_valid_xml ( $xml ) {
    libxml_use_internal_errors( true );

    $doc = new DOMDocument('1.0', 'utf-8');

    $doc->loadXML( $xml );

    $errors = libxml_get_errors();

    return empty( $errors );
}
?>

4

According to the php.net, if you load the libxml can find out what the mistakes are.

Example:

<?php
libxml_use_internal_errors(true);

$sxe = simplexml_load_string("<?xml version='1.0'><broken><xml></broken>");

if ($sxe === false) {

  echo "Erro carregando XML\n";

  foreach(libxml_get_errors() as $error) {
    echo "\t", $error->message;
  }
}
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.