How to fix XML "Opening and ending tag mismatch error"?

How to fix XML "Opening and ending tag mismatch error"?

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

How to fix XML "Opening and ending tag mismatch error"?

When simplexml_load_file() throws an "Opening and ending tag mismatch" error, it usually means the parser has encountered a malformed structure where a closing tag does not match the most recent unclosed opening tag. The error message is often cryptic: Opening and ending tag mismatch: div line 45. This indicates that on line 45, the parser saw a </div> tag, but the stack of currently open tags was expecting something else, like a span or an empty string if tags are nested incorrectly.

The core issue in the provided code snippet is that it attempts to repair the file by blindly appending a closing tag (</$tag>) to the line where the error was detected. This approach fails for several reasons. First, the error message format varies. Sometimes the mismatched tag is explicitly named, but often, especially with deeply nested structures or empty tags, the parser reports the expected closing tag rather than the one that actually closed the element incorrectly. Second, simply appending a closing tag to a line might result in invalid syntax if that line already contains content that needs to be wrapped properly or if the mismatch occurred due to missing opening tags earlier in the file.

A more robust strategy involves using libxml_use_internal_errors(true) to capture all errors, not just the first one. In many cases of malformed XML, a single "mismatch" error is the symptom of a cascade of issues starting from the root element or an ancestor tag. If you fix only the reported line without validating the structure upstream, the parser will throw a new error at the next load attempt.

Here is a refined approach to fixing these files programmatically:

libxml_use_internal_errors(true);
$xml = @simplexml_load_file($temp_name);

$errors = libxml_get_errors();
$fixed = false;

foreach ($errors as $error) {
    if (strpos($error->message, 'Opening and ending tag mismatch') !== false) {
        // Extract the tag name mentioned in the error. 
        // This is usually the tag that failed to close properly or the one that closed wrongly.
        preg_match('/Mismatch: (.*) on line/', $error->message, $matches);
        
        if (isset($matches[1])) {
            $tag = trim($matches[1]);
            $line = $error->line;
            
            // Read the file into an array to manipulate specific lines
            $lines = file($temp_name, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            
            // Adjust for 0-based indexing if reading with file() vs 1-based line numbers in error
            // Also ensure we don't go out of bounds
            if ($line <= count($lines)) {
                $original_line = $lines[$line - 1];
                
                // Attempt to reconstruct the missing closing tag logic here.
                // However, blindly appending is risky. A safer bet for automated repair 
                // often involves checking if the line ends with < and wrapping it,
                // or simply ensuring the specific mismatched tag is closed.
                
                // Example heuristic: If the error says "div" mismatch, try to ensure </div> exists.
                // But often, the real fix is removing the offending closing tag that caused the stack overflow,
                // OR adding a missing opening tag. Determining direction without full AST analysis is hard.
                
                // A pragmatic fallback for automated scripts: 
                // Remove the specific mismatched closing tag if it exists on that line, 
                // assuming it was the cause of the stack imbalance.
                if (strpos($original_line, '</' . $tag . '>') !== false) {
                    $lines[$line - 1] = preg_replace('/<\/' . preg_quote($tag) . '>\s*$/i', '', $original_line);
                    file_put_contents($temp_name, implode("\n", $lines));
                    echo "Fixed line {$line}: removed mismatched closing tag.\n";
                    $fixed = true;
                } else {
                    // If the tag isn't present to be removed, it likely needs to be added.
                    // But adding blindly is dangerous. 
                    echo "Line {$line} does not contain expected closing tag for repair.\n";
                }
            }
        }
    }
}

// Always check if there are remaining errors after the first fix
if (libxml_get_last_error()) {
    $last = libxml_get_last_error();
    echo "Error persists: " . libxml_get_errors()[0]->message . "\n";
} else {
    echo "XML repaired successfully.\n";
}

The critical trade-off here is between automation and accuracy. XML validation is inherently fragile; a single missing bracket can break thousands of lines. The code above attempts to remove the offending closing tag if it exists, which often resolves the immediate stack mismatch. However, this assumes the root cause was an extra closing tag. If the error stems from a missing opening tag earlier in the file, removing the closing tag might result in unclosed elements downstream, causing new errors when you reload the file.

For large files with thousands of lines, memory usage is also a concern. Loading the entire file into memory via file() is generally fine for text up to several gigabytes on modern systems, but if the dataset grows significantly larger, streaming parsers or DOMDocument with specific error handlers might be necessary. Another pitfall is modifying the original file directly during parsing; always write to a temporary buffer first and only overwrite the source once validation confirms success.

If you are building a processing pipeline where data integrity is paramount, consider using DOMDocument instead of SimpleXML. DOMDocument provides more granular access to the DOM tree and can sometimes give clearer error locations regarding node types (e.g., distinguishing between an element content mismatch and a character entity issue). Additionally, tools like xmllint from the libxml2 package offer command-line alternatives that can validate and repair files without writing custom PHP logic:

xmllint --noout --recover malformed.xml fixed.xml

Using --recover allows xmllint to attempt automatic correction of syntax errors, often handling complex nesting issues better than a simple string manipulation script. If you need to process these files within a Laravel application, ensure your service layer handles file locking and temporary resource cleanup to prevent race conditions or disk space exhaustion during mass repairs.

Our network