kostya572
kostya572

Reputation: 169

PHP Out-of-memory when parsing very large xml file 2.77 GB

when I am parsing 14 MB xml file everything works well, but when I need to parse 2.77 GB server crashes with out-of-memory.

I tried to add memory and execution time with:

ini_set('max_execution_time', 600);
set_time_limit("600");
ini_set("memory_limit","1024M");

it works unlimited without end

Here is piece of code using SimpleXML:

$xml = simplexml_load_file("detailed_data.xml");
if (!$xml) return "error loading xml";
print('<pre>');
foreach ($xml->art as $v1) {
    $intid = $v1->attributes()->int_id[0];
    $booktitle = $v1->text_description->hidden->{'title-info'}->{'book-title'};
    //echo "booktitle:$booktitle = ";
    $added = $v1->attributes()->added[0];
    $lastrelease = $v1->attributes()->last_release[0];

Also tried with XMLReader:

$reader = new XMLReader();  
$reader->open('detailed_data.xml');
print('<pre>');
while ($reader->read()) {

    if ($reader->nodeType == XMLReader::ELEMENT && $reader->name == 'art') {  

    $v1 = new SimpleXMLElement($reader->readOuterXML());  

    $intid = $v1->attributes()->int_id[0];

    $booktitle = $v1->text_description->hidden->{'title-info'}->{'book-title'};
    //echo "booktitle:$booktitle = ";

    $added = $v1->attributes()->added[0];

Output of command head detailed_data.xml:

<?xml version="1.0" encoding="UTF-8"?><litres-updates>

<art int_id="118915" added="2007-04-03 16:18:00" price="59.90" cover="jpg" last_release="2011-10-13 12:56:26" on_sale="1" file_id="3804925" chars="791605" type="0" file="3804925" show_preview="4" allow_read="1" lvl="3"><text_description><hidden><title-info><genre>sf_social</genre><genre>sf_history</genre><author><first-name>Марина и Сергей</first-name><last-name>Дяченко</last-name><id>e00dfc87-2a80-102a-9ae1-2dfe723fe7c7</id></author><book-title>Армагед-дом</book-title> <annotation><p>Мир на пороховой бочке, и несколько раз за век эта бочка взрывается Апокалипсисом. Из моря выходят чудовища, звезда Полынь опрокидывается в реки, превращая воду в кровь, ангел трубит в трубу над пепелищами. Лишь загадочные Врата сумеют спасти живых, чтобы люди могли после катастрофы отсроить жизнь заново – если, конечно, успеют войти в эти Врата. Мир привык, потому что привыкают ко всему. Лгут депутаты, мудрствуют спецслужбы, защищаются диссертации, рождаются дети. И конечно же, выдаются спецпропуска во Врата. Все как всегда, все как везде; регулярный, обыденный, ужасный Армагеддон, ставший для его обитателей Армагед-домом.</p>
<p>Жизнь главной героини – тому порука.</p>
<p>И тем не менее…</p>
</annotation><date value="1999-01-01">1999</date> <coverpage><image href="#cover.jpg"/></coverpage><lang>ru</lang> </title-info> <document-info><author><first-name>Roland</first-name> <last-name/> </author> <program-used>FB Editor v2.0</program-used> <date value="2008-11-28">28 November 2008</date> <src-url>http://www.litres.ru/pages/biblio_book/?art=118915</src-url><src-ocr>Текст предоставлен правообладателем</src-ocr> <id>30783516-71df-4d51-84c5-ceb7e938fa87</id></document-info> <publish-info><book-name>Армагед-дом</book-name> <publisher>Эксмо</publisher> <city>Москва</city> <year>2005</year> <isbn>5-699-14200-2</isbn> <sequence name="Триумвират"/></publish-info></hidden></text_description><year_rating quantity="168776"/><arts_relations><art_relation rel_art="4578560" relation="4"/><art_relation rel_art="4578560" relation="3"/></arts_relations><authors><author id="e00dfc87-2a80-102a-9ae1-2dfe723fe7c7"><subject_id>44608</subject_id><url>marina-i-sergey-dyachenko/</url><first-name>Марина и Сергей</first-name><middle-name></middle-name><last-name>Дяченко</last-name><full-name-rodit>Марины и Сергея Дяченко</full-name-rodit><lvl>4</lvl><relation>0</relation></author><author id="8488af72-967f-102a-94d5-07de47c81719"><subject_id>58188</subject_id><url></url><first-name>Литагент</first-name><middle-name></middle-name><last-name>Г.Л. Олди</last-name><full-name-rodit></full-name-rodit><lvl>1</lvl><relation>2</relation></author></authors></art>

<art int_id="118916" added="2007-04-03 16:18:04" price="59.90" cover="jpg" last_release="2011-10-14 19:38:55" on_sale="1" file_id="3809145" chars="691436" type="0" file="3809145" show_preview="4" allow_read="1" lvl="3"><text_description><hidden><title-info><genre>magician_book</genre><author><first-name>Марина и Сергей</first-name><last-name>Дяченко</last-name><id>e00dfc87-2a80-102a-9ae1-2dfe723fe7c7</id></author><book-title>Скрут</book-title> <annotation><p>В довольно-таки мрачном фэнтезийном мире зарождается довольно-таки светлая и романтическая любовь… И, возможно, они жили бы долго и счастливо и умерли в один день – если бы в ветвях зловещего леса не жил, ожидая своего часа, могущественный и безжалостный, с довольно-таки странными представлениями о справедливости – Скрут…</p>
</annotation><date value="1997-01-01">1997</date> <coverpage><image href="#cover.jpg"/></coverpage><lang>ru</lang> </title-info> <document-info><author><first-name>Consul</first-name> <last-name/> <email>[email protected]</email> </author> <program-used>FB Tools, FB Writer v1.1</program-used> <date value="2003-10-25">2003-10-25</date> <src-url>http://www.litres.ru/pages/biblio_book/?art=118916</src-url><src-url>http://www.aldebaran.ru/</src-url> <id>0fe2dba8-1890-44f1-96e6-544611df0f0a</id> <version>1.0</version> </document-info> <publish-info><year>2003</year> <sequence number="00" name="Нить времен"/></publish-info></hidden></text_description><year_rating quantity="71722"/><arts_relations></arts_relations><authors><author id="e00dfc87-2a80-102a-9ae1-2dfe723fe7c7"><subject_id>44608</subject_id><url>marina-i-sergey-dyachenko/</url><first-name>Марина и Сергей</first-name><middle-name></middle-name><last-name>Дяченко</last-name><full-name-rodit>Марины и Сергея Дяченко</full-name-rodit><lvl>4</lvl><relation>0</relation></author></authors></art>

Maybe I could split big 2.77 GB file to smaller parts?

Upvotes: 1

Views: 752

Answers (1)

kostya572
kostya572

Reputation: 169

This line helped me:

$reader->open('compress.zlib://detailed_data.xml.gz');

Opening compressed file detailed_data.xml.gz with size 544.2 MB against uncompressed file detailed_data.xml with size 2.77 GB solved the issue.

Upvotes: 1

Related Questions