Home > php教程 > php手册 > Regarding the problem of data export timeout

Regarding the problem of data export timeout

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-08-15 16:49:57
Original
1396 people have browsed it

In actual work, we often need to export reports. When the amount of exported data is too large, we often encounter timeout and memory overflow problems.
Solution 1

Timeout available: set_time_limit(0) solved.
Memory overflow is available: ini_set('memory_limit', 'custom memory').

Solution 2

Optimizers use databases or files to cache intermediate results.

Solution 3

Use Ajax to make multiple requests, write files, and download files. The effect is as shown above (the effect picture is a gif and cannot be uploaded, please use the link below to view).

(Option 3) Provide you with a Demo

Design ideas

1. We split it into 100 requests. The request is successful and the progress bar advances by 1%.
2. Each request requires writing to the file, and then appending to the file.
3. When the file is written, the download button is displayed, click to download.

Function points

1. Two progress bar styles.
2. Jquery Ajax.
3. Write data to CSV.
4. Download the file.

Page style: Bootstrap.

The code is as follows: <?php<br /> /**<br /> * Export CSV file<br /> * @param array $data Data<br /> * @param array $header_data First row of data<br /> * @param string $file_name File name<br /> * @param int $type $type Category<br /> * * @return string<br /> ​​*/<br /> Function _export_csv($data = [], $header_data = [], $file_name = '', $type = 0)<br /> {<br />          $fp = fopen($file_name, 'a+');<br /> If (($type != 1) && !empty($header_data)) {<br /> foreach ($header_data as $key => $value) {<br>                 $header_data[$key] = iconv('utf-8', 'gbk', $value);<br>              }<br>                    fputcsv($fp, $header_data);<br>         }<br>          $num = 0;<br> ​​​​//Every $limit line, refresh the output buffer, not too big, not too small<br>         $limit = 100000;<br> ​​​​//Get data line by line without wasting memory<br>         $count = count($data);<br> If ($count > 0) {<br> for ($i = 0; $i < $count; $i++) {<br />                    $num++;<br />                         // Refresh the output buffer to prevent problems caused by too much data<br /> If ($limit == $num) {<br />                                                                                                                                                       flush();<br />                      $num = 0;<br />                 }<br />                    $row = $data[$i];<br /> foreach ($row as $key => $value) {<br>                    $row[$key] = iconv('utf-8', 'gbk', $value);<br>                 }<br>                 fputcsv($fp, $row);<br>             }<br>         }<br>         fclose($fp);<br>     }<br> <br>     /**<br> * Download file <br> * @param string $file_url file address<br> * * @return string<br> ​​*/<br>     function _download_file ($file_url = '')<br>     {<br>         if (!isset($file_url) || trim($file_url)=='') {<br>             die('File URL is empty.');<br>         }<br>         if (!file_exists($file_url)) {<br>             die('File does not exist.');<br>         }<br>         $file_name = 'down_'.date('YmdHis', time());<br>         $file_type = fopen($file_url,'r'); //打开文件<br>         //输入文件标签<br>         header("Content-type: application/octet-stream");<br>         header("Accept-Ranges: bytes");<br>         header("Accept-Length: ".filesize($file_url));<br>         header("Content-Disposition: attachment; filename=".$file_name);<br>         //输出文件内容<br>         echo fread($file_type, filesize($file_url));<br>         fclose($file_type);<br>     }<br> <br>     //以后是逻辑代码,大家可以根据自己的需求进行编写。<br>         $path = '文件的绝对地址'; //path 是存放文件的绝对地址。<br>     if (isset($_POST['start'])) {<br>           //每一个单独的请求,要保证文件名是唯一的,因为后面要继续进行追加。<br>               $file_name = 'demo.csv';<br>         //获取数据,根据自己的业务逻辑,去数据库获取数据。<br>         $data        = [];<br>         $header_data = ['执行时间', '随机数']; //首行数据,表头<br>         //模拟数据如下:<br>         for ($i=0; $i<=100; $i++) {<br />             $data[$i]['time'] = date('Y-m-d H:i:s', time());<br />             $data[$i]['num']  = mt_rand(1000,9999);<br />         }<br />         $type = ($_POST['start'] != '0') ? 1 : 0 ;<br />         //开始将数据写入到文件中<br />         _export_csv($data, $header_data, $path.$file_name, $type);<br />         //假设第100次 写入完毕,那么就可以进行下载文件啦。<br /> //可以先获取需要导出的总量,然后根据实际情况进行拆分数据,每次获取成功,进度条会显示进度。<br /> if ($_POST[&#039;start&#039;] == 100) {<br /> die(json_encode([&#039;code&#039; => 'ok', 'file_path' => '/index.php?op=down&f='.$file_name]));<br>         } else {<br>             die(json_encode(['code' => 'no']));<br>         }<br>     }<br> <br>     //简单的导出逻辑,可根据实际情况,进行开发。<br>     if (($_GET['op'] == 'down') && !empty($_GET['f'])) {<br>             _download_file($path.$_GET['f']);<br>             exit;<br>     }<br> ?><br> <!DOCTYPE html><br> <html lang="zh-CN"><br>     <head><br>       <meta charset="utf-8"><br>         <meta http-equiv="X-UA-Compatible" content="IE=edge"><br>         <meta name="viewport" content="width=device-width, initial-scale=1"><br>         <meta name="description" content="Demo"><br>         <meta name="keywords" content=""><br>         <!-- 新 Bootstrap 核心 CSS 文件 --><br>         <link rel="stylesheet" href="//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css"><br>         <!-- jQuery --><br>         <script src="//cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script><br>         <!-- Title --><br>         <title>Demo</title><br>     </head><br>     <body><br>         <div class="container"><br>             <div class="row"><br>                 <div class="col-lg-12" style="margin-top:20px"><br>                     <a id="export_file" href="javascript:void(0);" class="btn btn-primary btn-lg active" role="button">导出CSV文件</a><br>                     <a id="download_file" style="display:none;" href="javascript:void(0);" class="btn btn-default btn-lg active" role="button">下载文件</a><br>                 </div><br>             </div><br> <br>             <div id="process_one" class="row" style="display:none"><br>                 <div class="col-lg-12" style="margin-top:20px"><br>                     <div class="progress"><br>                       <div id="progress-bar-one" class="progress-bar progress-bar-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 0%"><br>                       </div><br>                     </div><br>                 </div><br>             </div><br> <br>             <div id="process_two" class="row" style="display:none"><br>                 <div class="col-lg-12" style="margin-top:20px"><br>                     <div class="progress"><br>                       <div id="progress-bar-two" class="progress-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"><br>                         60%<br>                       </div><br>                     </div><br>                 </div><br>             </div><br>         </div><br> <script><br>           $(document).ready(function () {<br>                            //Export CSV file<br>                 $("#export_file").click(function(){<br>                   _get_data(0);<br>              });<br> <br> // The method of getting data 数据 Function _get_data(start)<br>                                                                             $.ajax({<br>                          type: "POST",<br> Url: 'Index.php', <br>                       data: {<br> ‘start’ : start<br>                                                          },<br> async: true,<br> DataType: "json",<br>                         beforeSend: function () {<br> $("#download_file").css('display', 'none');<br>                                                                                                                                                                                                                                                                                                                                   success: function (result) {<br> If (result.code == 'ok') {<br>                                                                                                                                                                                                                                                              through                                     $("#process_one").css('display', 'none');<br>                                                                                                                                                                                                                                                                   start ++;<br>                                 _get_data(start);<br>                                 $("#progress-bar-one").css("width", start+'%');<br>                                 $("#progress-bar-two").css("width", start+'%');<br>                                 $("#progress-bar-two").html(start+'%');<br>                             }<br>                         },<br>                         error: function() {<br>                             alert("Server Error~");<br>                         }<br>                     });<br>             }<br>         });<br>     </script><br>     </body><br> </html>温馨提示:
Demo 仅供参考,具体开发,请根据需求,严谨处理。

Thanks ~

来源:http://mp.weixin.qq.com/s?__biz=MjM5NDM4MDIwNw==&mid=2448834649&idx=1&sn=3be1ef996a9fcf3f4082decd6434a048#rd

更多【干货分享】,请关注我的个人订阅号。

Regarding the problem of data export timeout

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template