Home  >  Article  >  Backend Development  >  Several examples of PHP reading the contents of csv files

Several examples of PHP reading the contents of csv files

WBOY
WBOYOriginal
2016-07-25 08:55:24944browse
  1. $file = fopen('windows_2011_s.csv','r');
  2. while ($data = fgetcsv($file)) { //Read one line of content in CSV each time
  3. //print_r($data); //This is an array. To get each data, just access the array subscript
  4. $goods_list[] = $data;
  5. }
  6. //print_r($goods_list);
  7. / * foreach ($goods_list as $arr){
  8. if ($arr[0]!=""){
  9. echo $arr[0]."
    ";
  10. }
  11. } */
  12. echo $goods_list[ 2][0];
  13. fclose($file);
  14. ?>
Copy the code

Example 2, read a certain line of data from the csv file.

  1. function get_file_line( $file_name, $line ){
  2. $n = 0;
  3. $handle = fopen($file_name,'r');
  4. if ($handle) {
  5. while (!feof($handle)) {
  6. ++$n; // bbs.it-home.org
  7. $out = fgets($handle, 4096);
  8. if($line==$n) break;
  9. }
  10. fclose($handle);
  11. }
  12. if( $line==$n) return $out;
  13. return false;
  14. }
  15. echo get_file_line("windows_2011_s.csv", 10);
  16. ?>
Copy Code

Example 3, read the csv file to specify the number of lines (line interval).

  1. function get_file_line( $file_name, $line_star, $line_end){
  2. $n = 0;
  3. $handle = fopen($file_name,"r");
  4. if ($handle) {
  5. while (!feof($handle)) {
  6. ++$n;
  7. $out = fgets($handle, 4096);
  8. if($line_star <= $n){
  9. $ling[] = $out ;
  10. }
  11. if ($line_end == $n) break;
  12. }
  13. fclose($handle);
  14. } // bbs.it-home.org
  15. if( $line_end==$n) return $ling;
  16. return false;
  17. }
  18. $aa = get_file_line("windows_2011_s.csv", 11, 20); //From line 11 to line 20
  19. foreach ($aa as $bb){
  20. echo $bb."< br>";
  21. }
  22. ?>
Copy code

Example 4, two methods provided by netizens, untested. method 1,

  1. //Read the contents of the csv file
  2. $handle=fopen("1.csv","r");
  3. while(!feof($handle)){
  4. $buffer= fgetss($handle,2048);
  5. $data=explode(",",$buffer);
  6. $num=count($data);
  7. for($i=0;$i<$num;$i++){
  8. print_r($data);
  9. }
  10. }
  11. ?>
Copy code

Method 2,

  1. //Read the contents of the csv file
  2. $handle=fopen("1.csv","r");
  3. $row=1;
  4. while($data=fgetcsv($ handle,1000,",")){
  5. $num=count($data);
  6. for($i=0;$i<$num;$i++){
  7. echo $data[$i];
  8. }
  9. $row++;
  10. }
  11. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn