1. Generate Cvs,fputcsv () format the rows as CSV and write to the file pointer
The code is as follows |
Copy Code |
<?php $list = Array ( ' Aaa,bbb,ccc,dddd ', ' 11,22,33 ', ' php ', ' Java ' ); $fp = fopen (' file.csv ', ' W '); foreach ($list as $line) { Fputcsv ($fp, Explode (', ', $line)); } Fclose ($FP); ?> |
Small hint, if you have a CSV in Chinese we need to pay attention to Chinese problems, otherwise Chinese garbled will be with you play Oh, the following gives an example to solve Chinese garbled.
The code is as follows |
Copy Code |
<?php /** by Www.111cn.net * * $row = 1; $handle = fopen ("File.csv", "R"); fgetcsv () resolves the read rows and finds the fields in CSV format and returns an array containing the fields. while ($data = Fgetcsv ($handle, 1000, ",")) { $num = count ($data); echo "<p> $num fields in line $row: <br>n"; $row + +; for ($c =0; $c < $num; $c + +) { Attention to Chinese garbled problem $data [$c]=iconv ("GBK", "Utf-8//ignore", $data [$c]); echo $data [$c]. "<br>n"; } } Fclose ($handle); ?> |
Read a row of data in a CSV file
The code is as follows |
Copy Code |
<?php function Get_file_line ($file _name, $line) { $n = 0; $handle = fopen ($file _name, ' R '); if ($handle) { while (!feof ($handle)) { + + $n; $out = Fgets ($handle, 4096); if ($line = = $n) break; } Fclose ($handle); } if ($line = = $n) return $out; return false; } Echo get_file_line ("Windows_2011_s.csv", 10); ?> |
Read CSV file number of lines (line range)
code is as follows |
copy code |
<?php function Get_file_line ($file _name, $line _star, $line _end) { $n = 0; $handle = fopen ($file _name, "R"); if ($hand Le) { while (!feof ($handle)) { + + $n; $out = Fgets ($handle, 4096); if ($line _star <= $n) { $ling [] = $ Out } if ($line _end = = $n) break; } Fclose ($handle); } if ($line _end== $n) return $ling return false; } $aa = Get_file_line ("Windows_2011_s.csv", 11, 20);//From line 11th to 20th foreach ($aa as $BB) { echo $bb. <br> "; } |