W3docs

libxml_get_last_error()

Today, we will be discussing the libxml_get_last_error() function in PHP. This function is used to retrieve the last error that was generated by the libxml

The libxml_get_last_error() function in PHP retrieves the last error generated by the libxml library — the parser that powers PHP's DOMDocument, SimpleXML, and XMLReader extensions. When you parse or validate malformed XML, libxml records what went wrong; this function lets you read the most recent of those records so you can show a useful message instead of a cryptic warning.

This page covers what the function returns, how to capture errors with libxml_use_internal_errors(), the properties of the error object, and when to reach for libxml_get_last_error() versus the related functions.

Syntax

libxml_get_last_error(): LibXMLError|false

The function takes no arguments. It returns:

  • A LibXMLError object describing the most recent error, or
  • false if no error has been recorded since the last call to libxml_clear_errors().

Why you need it

By default, libxml emits errors as PHP warnings, which clutter your output and are hard to handle programmatically. The usual pattern is:

  1. Call libxml_use_internal_errors(true) to suppress the warnings and store errors in an internal buffer instead.
  2. Parse or validate your XML.
  3. Read the buffer with libxml_get_last_error() (most recent only) or libxml_get_errors() (all of them).
  4. Clear the buffer with libxml_clear_errors() so the next operation starts clean.

Use libxml_get_last_error() when you only care about what just failed — for example, reporting why a single parse call did not succeed.

The LibXMLError object

The returned object exposes these public properties:

PropertyDescription
levelSeverity: LIBXML_ERR_WARNING (1), LIBXML_ERR_ERROR (2), or LIBXML_ERR_FATAL (3).
codeThe libxml error code (an integer).
messageA human-readable description of the error.
fileThe file that triggered the error, or an empty string when parsing a string.
lineThe line number where the error occurred.
columnThe column number where the error occurred.

Example: catching a parse error

This example parses an intentionally broken XML string (a missing closing tag), then prints the captured error. It is fully self-contained — no external file is needed:

<?php
// Store libxml errors in an internal buffer instead of emitting warnings
libxml_use_internal_errors(true);

// This XML is malformed: <title> is never closed
$badXml = '<book><title>PHP</book>';

$doc = new DOMDocument();
$doc->loadXML($badXml);

$error = libxml_get_last_error();

if ($error !== false) {
    echo "Error level:  " . $error->level   . PHP_EOL;
    echo "Error code:   " . $error->code    . PHP_EOL;
    echo "Line:         " . $error->line     . PHP_EOL;
    echo "Message:      " . trim($error->message) . PHP_EOL;
} else {
    echo "The XML parsed without errors." . PHP_EOL;
}

// Always clear the buffer when you are done with it
libxml_clear_errors();
?>

Output:

Error level:  3
Line:         1
Message:      Premature end of data in tag book line 1

The exact code, column, and message wording depend on your libxml version, but the structure is always the same. level is 3 (LIBXML_ERR_FATAL) because the unclosed tag makes the document unparseable. (code is omitted from the output above only because its value is version-specific.)

Example: validating against a schema

A common real-world use is reporting why a document failed schema validation:

<?php
libxml_use_internal_errors(true);

$doc = new DOMDocument();
$doc->load('example.xml');

if ($doc->schemaValidate('example.xsd')) {
    echo "The XML document is valid.";
} else {
    $error = libxml_get_last_error();
    if ($error !== false) {
        echo "Validation failed: " . trim($error->message);
    }
}

libxml_clear_errors();
?>

Here we check the return value of libxml_get_last_error() against false before touching $error->message — accessing a property on false would raise its own warning.

Common gotchas

  • You must enable internal error handling first. Without libxml_use_internal_errors(true), libxml prints warnings and the internal buffer stays empty, so libxml_get_last_error() returns false.
  • Clear the buffer between operations. Errors accumulate. If you do not call libxml_clear_errors(), a later call to libxml_get_last_error() may return a stale error from an earlier parse.
  • Last means last, not "this call". The function returns whatever is at the end of the buffer, regardless of which parse produced it.

For broader context on parsing XML in PHP, see The XML DOM in PHP and SimpleXML.

Conclusion

libxml_get_last_error() gives you programmatic access to the most recent XML parsing or validation error, turning silent failures and noisy warnings into actionable messages. Pair it with libxml_use_internal_errors() to capture errors and libxml_clear_errors() to reset the buffer, and use libxml_get_errors() when you need the full list rather than just the latest.

Practice

Practice
What does the libxml_get_last_error() function do in PHP?
What does the libxml_get_last_error() function do in PHP?
Was this page helpful?