PHP Function Reference

PHP libxml_get_last_error() Function



The PHP libxml_get_last_error() function retrieves last error from libxml.

Syntax

libxml_get_last_error()

Parameters

No parameter is required.

Return Value

Returns a LibXMLError object if there is any error in the buffer, false otherwise.

Example: libxml_get_last_error() example

The example below shows the usage of libxml_get_last_error() function.

<?php
libxml_use_internal_errors(true);

//contains mismatched tags
$xmlstr = <<<XML
<mail> 
  <To>John Smith</too>
  <From>Marry G.</From>
  <Subject>Happy Birthday</Subject>
  <body>Happy birthday. Live your life with smiles.</Body>
</mail> 
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
  $error = libxml_get_last_error();

  //displaying last error occurred
  print_r($error);

  //clearing the libxml error buffer
  libxml_clear_errors();
}
?>

The output of the above code will be:

LibXMLError Object
(
    [level] => 3
    [code] => 76
    [column] => 59
    [message] => Opening and ending tag mismatch: body line 2 and Body

    [file] => 
    [line] => 5
)

Example: building a simple error handler

The example below shows how to build a simple libxml error handler.

<?php
libxml_use_internal_errors(true);

//contains mismatched tags
$xmlstr = <<<XML
<mail> 
  <To>John Smith</too>
  <From>Marry G.</From>
  <Subject>Happy Birthday</Subject>
  <body>Happy birthday. Live your life with smiles.</Body>
</mail> 
XML;

$doc = simplexml_load_string($xmlstr);
$xml = explode("\n", $xmlstr);

if ($doc === false) {
  $error = libxml_get_last_error();

  //displaying last error occurred
  echo display_xml_error($error, $xml);

  //clearing the libxml error buffer
  libxml_clear_errors();
}

//function to display last error message
function display_xml_error($error, $xml) {
  $message = "";
  switch ($error->level) {
    case LIBXML_ERR_WARNING:
      $message .= "Warning $error->code: ";
      break;
    case LIBXML_ERR_ERROR:
      $message .= "Error $error->code: ";
      break;
    case LIBXML_ERR_FATAL:
      $message .= "Fatal Error $error->code: ";
      break;
  }

  $message .= trim($error->message) .
    "\n Line: $error->line" .
    "\n Column: $error->column";

  if ($error->file) {
    $message .= "\n File: $error->file";
  }

    return $message;
}
?>

The output of the above code will be:

Fatal Error 76: Opening and ending tag mismatch: body line 2 and Body
 Line: 5
 Column: 59

❮ PHP Libxml Reference