php csv操作

mac2022-06-30  94

csv的写入数据:

[php] view plain copy print ? $data = array( array('qq号','登录时间','名称'), array('123456','2012-08-21 15:21:10'.chr(1),'我是来测试的'), array('56788','2012-08-21 18:21:20 '.chr(1),'test测试数据'), array('321789','2012-08-21 11:21:25 '.chr(1),'HELLO') );$filename = "./file/test.csv"; if( !file_exists( $filename ) ){ file_put_contents($filename, ''); }$file = fopen($filename, 'w'); foreach ( $data as $val ){ if( false === fputcsv($file, $val) ){ die('写入数据失败'); }}fclose($file); $data = array( array('qq号','登录时间','名称'), array('123456','2012-08-21 15:21:10'.chr(1),'我是来测试的'), array('56788','2012-08-21 18:21:20 '.chr(1),'test测试数据'), array('321789','2012-08-21 11:21:25 '.chr(1),'HELLO') ); $filename = "./file/test.csv"; if( !file_exists( $filename ) ){ file_put_contents($filename, ''); } $file = fopen($filename, 'w'); foreach ( $data as $val ){ if( false === fputcsv($file, $val) ){ die('写入数据失败'); } } fclose($file);

在写入到csv的时候我的日期格式出现了问题,只显示格式为:2011/06/05 12:02。导致我的秒数不存在了,所以在时间的后面都要加上chr(1)来得到正确的格式

csv读数据:

[php] view plain copy print ? $file = fopen($filename, 'w') or die('打开文件失败'); //读数据 $file = fopen($filename, 'r'); while ( $val = fgetcsv($file) ){ print_r($val); }fclose($file); $file = fopen($filename, 'w') or die('打开文件失败'); //读数据 $file = fopen($filename, 'r'); while ( $val = fgetcsv($file) ){ print_r($val); } fclose($file);

csv的下载:

[php] view plain copy print ? $data = array( array('qq号','登录时间','名称'), array('123456','2012-08-21 15:21:10'.chr(1),'我是来测试的'), array('56788','2012-08-21 18:21:20 '.chr(1),'test测试数据'), array('321789','2012-08-21 11:21:25 '.chr(1),'HELLO') ); //下载功能 $date = time(); header("Content-Type: text/csv"); header("Content-Disposition: attachment; filename=".$date.".csv"); header('Cache-Control:must-revalidate,post-check=0,pre-check=0'); header('Expires:0'); header('Pragma:public'); foreach ( $data as $val ){ echo implode(",", $val)."\n"; }  ----------------------------------------------------------------------------

<?php$filename = "./creattest.csv"; //读数据 $file = fopen($filename, 'r'); $prex = "linpre";while ( $val = fgetcsv($file) ){ print_r($val); echo "<hr/>"; $val_list[] = $val;}$val_list[0][0] = $prex.$val_list[0][0];$val_list[1][0] = $prex.$val_list[1][0];echo $val_list[0][0]."------------";$file = fopen($filename, 'w'); foreach ( $val_list as $list ){ if( false === fputcsv($file, $list) ){ die('写入数据失败'); }}fclose($file);

转载于:https://www.cnblogs.com/alex-13/p/4014250.html

相关资源:php操作csv文件代码实例汇总
最新回复(0)