PHP CSV operation class code

  • 2020-03-31 20:12:07
  • OfStack

Please click on the back address download: (link: http://xiazai.jb51.net/200912/yuanma/csvdatafile.rar)
Instructions are as follows:

1. Generate CSV files

 
require "./include/csvdatafile.php"; 

set_time_limit(200); 
header("Content-type: application/RFC822"); 
header('Content-Disposition: attachment; filename=export.csv'); 

$arr_export_titles = array(" Student no. "," Student id "," The student's name "); 

$csvfile = new csvDataFile("", ",", "w"); 
echo $csvfile->printline($arr_export_titles); 
//Methods a
$print_data1[] = 1; 
$print_data1[] = "039413301"; 
$print_data1[] = " Zhang SAN "; 
echo $csvfile->printline($print_data1); 

$print_data2[] = 2; 
$print_data2[] = "039413302"; 
$print_data2[] = " Li si "; 
echo $csvfile->printline($print_data2); 


$print_data3[] = 3; 
$print_data3[] = "039413303"; 
$print_data3[] = " Cathy "; 
echo $csvfile->printline($print_data3); 


//Method 2
$print_data[1][] = 1; 
$print_data[1][] = "039413301"; 
$print_data[1][] = " Zhang SAN "; 
$print_data[2][] = 2; 
$print_data[2][] = "039413302"; 
$print_data[2][] = " Li si "; 
$print_data[3][] = 3; 
$print_data[3][] = "039413303"; 
$print_data[3][] = " Cathy "; 
echo $csvfile->printcsv($print_data); 





2. Open CSV to read data



code
 
require "./include/csvdatafile.php"; 

$filename = "E:/development/csvfile/datefile.csv"; 

// Read file source 
$handle = fopen($filename, "r"); 
$contents = fread($handle, filesize($filename)); 
fclose($handle); 

// format content for special chars 
$contents = @addslashes($contents); 
$contents = @str_replace(',', ' ,', $contents); 
$contents = @stripslashes($contents); 

// Write to new file 
$handle = @fopen($filename, "w"); 
@fwrite($handle, $contents); 
@fclose($handle); 

$fd = @fopen($filename, "rb"); 
$first_line = str_replace(' ,',',',str_replace('"','',trim(@fgets($fd, 1000)))) ; 
@fclose($fd); 

if($first_line != " Student no. , Student id , The student's name ") { 
$pass = false; 
} 

if($pass){ 
$csv = new csvDataFile($filename); 
while($csv->next_Row()) { 
$userid = trim($csv->f(' Student no. ')); 
$classno = trim($csv->f(' Student id ')); 
$username = trim($csv->f(' The student's name ')); 
} 
} 

Related articles: