How to use XMLReader in PHP?

How to use XMLReader in PHP?

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

Stefan Bogdanescu

Founder & Senior Architect

How to use XMLReader in PHP?

When dealing with large XML files, SimpleXML often hits performance walls or memory limits because it attempts to load the entire document structure into memory at once. If you are facing issues where SimpleXML fails to parse a file that otherwise looks syntactically correct, switching to XMLReader is a pragmatic solution. As an event-based parser, XMLReader processes the document node-by-node, streaming data without holding the full tree in RAM. This approach is significantly more memory-efficient for large datasets and often resolves parsing errors caused by internal buffering issues in simpler parsers.

The XML file you provided demonstrates a standard structure with a root <products> element containing metadata like <last_updated> and multiple <product> entries, each with several child elements. To extract data from this using XMLReader, you do not instantiate the parser with the whole file path in a way that loads everything immediately; instead, you create an instance and move through it manually using navigation methods.

Here is the basic pattern for initializing the reader and iterating through the document:

<?php
$filename = 'products.xml';
$reader = new XMLReader();

if ($reader->open($filename)) {
    $reader->moveToElement('product'); // Skip to the first product node
    
    while ($reader->read()) {
        if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'product') {
            // Start processing a new product block
            
            // Read and store the last_updated value at the top level if needed
            if ($reader->name === 'last_updated' && !isset($data['last_updated'])) {
                $data['last_updated'] = $reader->value;
            }
            
            // Process element_1 through element_4
            $productData = [];
            while ($reader->read()) {
                if ($reader->nodeType === XMLReader::ELEMENT && !empty($reader->name)) {
                    // Assuming these are self-closing or empty of text content in your schema,
                    // but if they contain text like 'foo', we capture the value.
                    $productData[$reader->name] = $reader->value;
                }
            }

            // Store the product data in your array
            $products[] = [
                'elements' => $productData,
                // Add other fields as needed
            ];
            
            // Move to the next sibling or break if no more products exist
            while ($reader->read() && $reader->nodeType !== XMLReader::ELEMENT) {
                continue;
            }
        }
    }
    
    $reader->close();
}

However, navigating manually using moveToElement and looping through read() can be verbose. A cleaner approach for your specific structure involves moving directly to the first child of the root and checking if you are inside a <product> tag before processing its children.

<?php
$reader = new XMLReader();
$data = ['last_updated' => null, 'products' => []];

if ($reader->open('products.xml')) {
    $reader->moveToElement('products'); // Move to root
    
    while ($reader->read()) {
        if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'product') {
            $currentProduct = [];
            
            // Read children of the product node
            $reader->read(); // Skip opening tag
            
            while ($reader->read() && $reader->nodeType === XMLReader::ELEMENT) {
                if (!empty($reader->name)) {
                    $currentProduct[$reader->name] = $reader->value;
                }
            }
            
            // Read the closing tag to stay in sync with the stream
            $reader->read(); 
            
            $data['products'][] = $currentProduct;
        }
    }
    
    // Handle the last_updated element which is a sibling of product
    if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'last_updated') {
        $data['last_updated'] = $reader->value;
    }
}

$reader->close();

A critical pitfall with XMLReader is maintaining state within the loop. The parser moves forward automatically with every read() call, so you must ensure your logic accounts for skipping opening tags and closing tags unless you explicitly want to process them. In the example above, we skip the opening tag of <product> and then read until we hit a non-element node (likely the closing tag) before storing the data.

Another consideration is encoding. Your source file specifies encoding="ISO-8859-1". PHP's default internal encoding handling usually respects the XML declaration when opening the stream, but if you encounter character set issues, ensure your database connection and storage layer are configured to handle these legacy encodings correctly. Storing ISO-8859-1 data directly into a UTF-8 database requires careful conversion or escaping during insertion to prevent garbled text.

For projects built on the Laravel framework, handling large XML imports often involves queuing the parsing process to avoid blocking the web server request. If you are integrating this logic into a backend service, consider using a job queue like Laravel Horizon to parse the file asynchronously. This prevents timeouts when processing massive catalogs and allows you to save results incrementally to a database as chunks are processed.

By leveraging XMLReader's streaming capabilities, you gain control over memory consumption and parsing speed, making it the robust choice for large-scale XML ingestion tasks where SimpleXML might falter.

Our network