Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.5k views
in Technique[技术] by (71.8m points)

php - How to write a large XML file to disk without storing it first in memory?

I have a symfony command that exports more than 100,000 lines from a database to an xml file.

In the current version of the php script everything is first put in RAM and then sent to a twig file which writes it to RAM (with the ob functions) and then everything is written to disk.

Here is the sample code snippet:

$results = $dbSession->query(/*SQL query*/);
$data = [];

foreach ($results as $row) {
  $data[] = $row;
}

file_put_contents(
  $xmlFilename,
  $twig->render($twigFileName,
      $data
  )
);

How can I stream directly from the database to the output file?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use Response class

  $xml = '<?xml version="1.0" encoding="UTF-8"?>';
  $xml .= 'xml content'; // add your  xml here

  $response = new Response($xml);
  $response->headers->set('Content-Type', 'xml');
    
  return $response;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...