In order to processing large XML files ( I do mean extremely large XML files ) in php, it is very memory hungry to use the PHP 5′ DomDocument. It would be much wiser to use XMLReader in this case. And I will demonstrate how to use this class in this post. Let’s setup some basic testing xml file to work with:
	Eric Lin
<address>Eric's Address</address>
	    Sue He
<address>Sue's Address</address>
The following is the PHP 5’s code to read the XML file:
$counter = 0;
$list = array();
$xmlReader = new XMLReader();
$xmlReader->open('testingfile.xml');
while($xmlReader->read())
{
	// check to ensure nodeType is an Element
	if($xmlReader->nodeType == XMLReader::ELEMENT)
	{
		if($xmlReader->localName == 'school')
		{
			$list[$counter]['id'] = $xmlReader->getAttribute('id');
		}

		if($xmlReader->localName == 'name')
		{
			// move to its textnode
			$xmlReader->read();
			$list[$counter]['name'] = $xmlReader->value;
		}

		if($xmlReader->localName == 'address')
		{
			// move to its textnode
			$xmlReader->read();
			$list[$counter]['address'] = $xmlReader->value;
			$counter++;
		}
	}
}
You now should get the data from XML in your desired format. This code is not as clean as using DomDocument, but it is very useful to handle really large files and you won’t have memory issues. Hope this helps….

Leave a Reply

Your email address will not be published. Required fields are marked *