首页 > 代码库 > php csv操作

php csv操作

csv的写入数据:

[php] view plaincopyprint?
  1. $data = http://www.mamicode.com/array(
  2. array(‘qq号‘,‘登录时间‘,‘名称‘),
  3. array(‘123456‘,‘2012-08-21 15:21:10‘.chr(1),‘我是来测试的‘),
  4. array(‘56788‘,‘2012-08-21 18:21:20 ‘.chr(1),‘test测试数据‘),
  5. array(‘321789‘,‘2012-08-21 11:21:25 ‘.chr(1),‘HELLO‘)
  6. );
  7. $filename = "./file/test.csv";
  8. if( !file_exists( $filename ) ){
  9. file_put_contents($filename, ‘‘);
  10. }
  11. $file = fopen($filename, ‘w‘);
  12. foreach ( $data as $val ){
  13. if( false === fputcsv($file, $val) ){
  14. die(‘写入数据失败‘);
  15. }
  16. }
  17. fclose($file);
$data = http://www.mamicode.com/array("./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 plaincopyprint?
  1. $file = fopen($filename, ‘w‘) or die(‘打开文件失败‘);
  2. //读数据
  3. $file = fopen($filename, ‘r‘);
  4. while ( $val = fgetcsv($file) ){
  5. print_r($val);
  6. }
  7. fclose($file);
$file = fopen($filename, ‘w‘) or die(‘打开文件失败‘);//读数据$file =  fopen($filename, ‘r‘);while ( $val = fgetcsv($file) ){	print_r($val);}fclose($file);

csv的下载:

[php] view plaincopyprint?
  1. $data = http://www.mamicode.com/array(
  2. array(‘qq号‘,‘登录时间‘,‘名称‘),
  3. array(‘123456‘,‘2012-08-21 15:21:10‘.chr(1),‘我是来测试的‘),
  4. array(‘56788‘,‘2012-08-21 18:21:20 ‘.chr(1),‘test测试数据‘),
  5. array(‘321789‘,‘2012-08-21 11:21:25 ‘.chr(1),‘HELLO‘)
  6. );
  7. //下载功能
  8. $date = time();
  9. header("Content-Type: text/csv");
  10. header("Content-Disposition: attachment; filename=".$date.".csv");
  11. header(‘Cache-Control:must-revalidate,post-check=0,pre-check=0‘);
  12. header(‘Expires:0‘);
  13. header(‘Pragma:public‘);
  14. foreach ( $data as $val ){
  15. echo implode(",", $val)."\n";
  16. }  
  17. ----------------------------------------------------------------------------
  18. <?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);

php csv操作