Back to results for “File System”
PHP › XML Handling in PHP

How can you efficiently parse an extremely large XML file that would be too large to comfortably load entirely into memory at once, using a streaming based approach like XMLReader?

Advanced

Answer

Loading an extremely large XML file entirely into memory at once, as both SimpleXML and DOM effectively do, can quickly exhaust available memory or become very slow when working with files containing millions of records, and the XMLReader extension instead provides a streaming, forward only approach, reading through the document incrementally piece by piece rather than loading the entire structure into memory simultaneously, letting you process even extremely large XML files using a relatively small, constant amount of memory regardless of the total file size.
$reader = new XMLReader();
$reader->open('huge_catalog.xml');

while ($reader->read()) {
    if ($reader->nodeType === XMLReader::ELEMENT && $reader->name === 'product') {
        // process one product element at a time
    }
}
Real-world example A data import system processes a multi gigabyte XML product catalog file using XMLReader, successfully importing every single product record while keeping memory usage low and constant throughout the entire process, which would not have been feasible using SimpleXML or DOM alone.

Common follow-ups: What are the tradeoffs of using a streaming parser like XMLReader compared to the simpler SimpleXML or DOM approaches?;Can XMLWriter be used similarly to generate a very large XML file without loading it entirely into memory?