Why I have memory issues when I use a non-tree XML parser? ( XML Parser)
I am finding my way with XML parsers, and I try now XML Parser. (I also testes XMLReader but I find it very slow).
As I read it has not any memory issues because it does not load the whole document in memory like DOM or SimpleXML.
I use this code for testing purposes replacing the working $data = fread($fp, 4096);
with $data = fread($fp, filesize($file));
to load the whole document and display it, not only a small amount of it.
When I do this I get this error Fatal error: Allowed memory size of 67108864 bytes exhausted
Can anyone clear my mind and share with me some knowledge regarding this ?
The XML file is 120mb.
<?php
// The XML file that you wish to be parsed
$file = "standard.xml";
// This function tells the parser what to do with the data once it reaches the contents
// that appear between tags.
function 开发者_高级运维contents($parser, $data){
echo $data;
}
// This function tells the parser to place a <b> where it finds a start tag.
function startTag($parser, $data){
echo "<b>";
}
// And this function tells the parser to replace the end tags with "<b><br />"
function endTag($parser, $data){
echo "</b><br />";
}
// These lines create the parser and then set the functions for the parser to use when
// reading the document.
$xml_parser = xml_parser_create();
// Sets the functions for start and end tags
xml_set_element_handler($xml_parser, "startTag", "endTag");
// Sets the function for the contents/data
xml_set_character_data_handler($xml_parser, "contents");
// Opens the file for reading
$fp = fopen($file, "r");
// Read the file and save its contents as the variable "data"
$data = fread($fp, filesize($file));
// This if statement does two things. 1) it parses the document according to our
// functions created above. 2) If the parse fails for some reason it returns an
// error message and also tells us which line the error occured at.
if(!(xml_parse($xml_parser, $data, feof($fp)))){
die("Error on line " . xml_get_current_line_number($xml_parser));
}
// Free the memory used to create the parser
xml_parser_free($xml_parser);
// Close the file when you're done reading it
fclose($fp);
?>
The line $data = fread($fp, filesize($file));
will read the whole file into memory. If you have 64MB of memory and the file is 120MB of size then i guess you can see why that fails.
Reread the docs for xml_parse and feed it with smaller chunks for data to work within your memory limit :)
精彩评论