从api导出csv
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
public function getRow() { $page=1; $agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)'; $curl = curl_init(); curl_setopt($curl,CURLOPT_HEADER,0); curl_setopt($curl,CURLOPT_RETURNTRANSFER,1); curl_setopt($curl,CURLOPT_HTTPHEADER,["Host: admin.binheng.com"]); curl_setopt($curl, CURLOPT_USERAGENT, $agent); curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false); curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false); $filename = 'dnfOnline'; $extension = '.csv'; $title = ['账号','密码']; // 头部设置 告诉浏览器下载文件 header("Content-Type: text/csv"); $filename = rawurlencode($filename); header("Content-Disposition: attachment; filename={$filename}{$extension}; filename*=UTF-8''{$filename}{$extension};"); header("Cache-Control: max-age=0"); // 打开输出流 $handle = fopen("php://output",'wb'); // 设置BOM,否则中文乱码 fwrite($handle,"\xEF\xBB\xBF"); // 写入头部 if (!empty($title)) { fputcsv($handle,$title,',','"',''); } while (true) { $http = 'http://192.168.123.134/api/page?page='.$page; curl_setopt($curl,CURLOPT_URL,$http); $content = curl_exec($curl); if (false==$content) { halt(curl_error($curl)); } $arr = json_decode($content,true); $arr = $arr['data']['data']; if ($page>1000 || empty($arr)) { break; } foreach ($arr as $item) { fputcsv($handle,$item,',','"',''); } $page++; } curl_close($curl); fclose($handle); exit(); } |
从数据(DB)导出到csv
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public function exportCsv() { $data = []; // 数据 $filename = 'dnfOnline'; $extension = '.csv'; $title = ['账号','密码']; // 头部设置 告诉浏览器下载文件 header("Content-Type: text/csv"); $filename = rawurlencode($filename); header("Content-Disposition: attachment; filename={$filename}{$extension}; filename*=UTF-8''{$filename}{$extension};"); header("Cache-Control: max-age=0"); // 打开输出流 $handle = fopen("php://output",'wb'); // 设置BOM,否则中文乱码 fwrite($handle,"\xEF\xBB\xBF"); // 写入头部 if (!empty($title)) { fputcsv($handle,$title,',','"',''); } foreach ($data as $item) { fputcsv($handle,$item,',','"',''); } fclose($handle); exit(); } |
csv导入到数据库
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public function importCsv() { $path = '文件路径'; foreach ($this->getLine($path) as $item) { // 写入数据库,使用框架的话,最好批量插入 Db::table('tableName')->data($item)->insert(); } exit(); } /** 生成器读取数据 * @param string $path * @return \Generator */ public function getLine($path='') { $handle = fopen($path,'rb'); try { /*while ($row = fgets($handle)) { //$row = utf8_encode($row); yield str_getcsv($row); }*/ while ($row = fgetcsv($handle)) { yield $row; } } finally { fclose($handle); } } |