Convert large XML file to CSV in PHP

I have a 50 megabyte xml file. I want to convert it to a CSV file, but most of the methods that I found exhaust the server’s memory. Is there a good way to do this using a stream method such as XMLreader.

+3
source share
7 answers

You want to use XmlReaderXML for parsing because it works as an event-based parser - for example. it does not load everything into memory, but reads when it moves through the input file.

+4
source

SAX-style parser is the most economical option:

http://php.net/xml_parse

$start_element_handler $end_element_handler , , .

, 50 , , .

php_value memory_limit 100M

.htaccess/httpd.conf php.ini.

+4

...

xml <domains><domain><name>myname.com</name></domain></domains>

$url = "http://mysite.com/my.xml";
  $returnData = file_get_contents($url);
  $xml = simplexml_load_file($url);

     $csv = 'my.csv';
     $path = '/var/www/html/';

  $domain = $xml->domains->domain;

      $fullpath = $path.$csv;
      $fp = fopen($fullpath, 'w');

    foreach ($xml->domains->domain as $domain) {

        fputcsv($fp, get_object_vars($domain),',','"');

    }

    fclose($fp);

       header('Content-Description: File Transfer');
           header('Content-Type: application/csv');
       header('Content-Disposition: attachment; filename='.basename($csv));
       header('Content-Transfer-Encoding: binary');
       header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
       header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
       header('Pragma: public');
       header('Content-Length: ' . filesize($fullpath));
       readfile($fullpath);

    exit;
    }
}
+1

? ini_set('memory_limit', '256M')

( )

0

PHP API, , , : XML Parser

, , , SAX. - . , .

0

XML XML, - PHP , . XML?

0

Source: https://habr.com/ru/post/1729823/


All Articles