Write Data for CSV:
[PHP]View Plaincopyprint?
- $data = Array (
- Array (' QQ number ',' login time ', 'name '),
- Array (' 123456 ',' 2012-08-21 15:21:10 '. Chr (1),' I'm here to test '),
- Array (' 56788 ',' 2012-08-21 18:21:20 '. Chr (1),' test data '),
- 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 (' Write data failed ');
- }
- }
- Fclose ($file);
$data = Array (' QQ number ', ' Login time ', ' name '), Array (' 123456 ', ' 2012-08-21 15:21:10 '. chr (1), ' I'm here to test '), Array (' 56788 ', ' 2012-08-21 18:21:20 '. chr (1), ' test data '), 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 (' Write Data Failed ')}} Fclose ($file);
There was a problem with my date format when I wrote to CSV, only the format was: 2011/06/05 12:02. Cause my number of seconds does not exist, so at the back of time to add Chr (1) to get the correct format
CSV Read data:
[PHP]View Plaincopyprint?
- $file = fopen ($filename, ' W ') or Die (' Open file failed ');
- Read data
- $file = fopen ($filename, ' R ');
- while ( $val = fgetcsv ($file)) {
- Print_r ($val);
- }
- Fclose ($file);
$file = fopen ($filename, ' w ') or Die (' Open file failed ');//Read Data $file = fopen ($filename, ' R '); while ($val = Fgetcsv ($file)) {pri Nt_r ($val);} Fclose ($file);
Download of CSV:
[PHP]View Plaincopyprint?
- $data = Array (
- Array (' QQ number ',' login time ', 'name '),
- Array (' 123456 ',' 2012-08-21 15:21:10 '. Chr (1),' I'm here to test '),
- Array (' 56788 ',' 2012-08-21 18:21:20 '. Chr (1),' test data '),
- Array (' 321789 ',' 2012-08-21 11:21:25 '. Chr (1),' HELLO ')
- );
- Download function
- $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";
Read data
$file = fopen ($filename, ' R ');
$prex = "Linpre";
while ($val = Fgetcsv ($file)) {
Print_r ($val);
echo "$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 (' Write data failed ');
}}
Fclose ($file);
PHP csv operation