dream12001 2016-09-12 17:20
浏览 23

使用foreach函数将CSV导出到文件夹

I have an php script, which i want to use to automatically export data from a certain mysql table, to a CSV file in a directory. The script is working fine and the files are saved in the right directory, but u want, that every order, exports to a separate CSV file.

Like:

  • 12-09-2016-05-21_csvexport_1.CSV < data from order 1
  • 12-09-2016-05-21_csvexport_2.CSV < data from order 2
  • And so on..

I want to run the script automatically with a cronjob. The orders to be exported as a separate csv file, can be selected with a date range. Like only create csv files from the last 2 days. It doesn't matter if the CSV files are going to overwrite. The order table looks like this:

id_order    date        customer
1       01-01-2016  1223
2       01-02-2016  1224
3       01-03-2016  1225
4       01-04-2016  1226
5       01-05-2016  1227

And the php script looks like this:

<?php
error_reporting(E_ALL ^ E_DEPRECATED);
$host = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'database';
$table = 'columns';
$file = 'csvexport';
$dir = 'csv';

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");    

function escape_csv_value($value) { 
$value = str_replace('"', '""', $value);
if ( preg_match( '/\|\
|,|"/', $value ) ) {
return '"' . str_replace( '"', '""', $value ) . '"';
} else { 
return $value;
} 
} 

$result = mysql_query("SHOW COLUMNS FROM ".$table."");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
    
$values = mysql_query("SELECT id_order, date, customer FROM orders");
while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= escape_csv_value($rowr[$j]).';'; 
}
$csv_output .= "
";
}
    
header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: attachment; filename=".$filename.".csv"); 

$filename = date("d-m-Y-i-s_", time()) . $file.".csv";

print $csv_output;
    file_put_contents($dir ."/".$filename, $csv_output);
}
?>

I hope someone can help me. Thanks in advance.

</div>
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
    • ¥15 数据可视化Python
    • ¥15 要给毕业设计添加扫码登录的功能!!有偿
    • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
    • ¥15 微信公众号自制会员卡没有收款渠道啊
    • ¥15 stable diffusion
    • ¥100 Jenkins自动化部署—悬赏100元
    • ¥15 关于#python#的问题:求帮写python代码
    • ¥20 MATLAB画图图形出现上下震荡的线条
    • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘