zoukankan      html  css  js  c++  java
  • PHP读取csv文件的内容

    一次性读取csv文件内所有行的数据

    <?php 
    $file = fopen('windows_2011_s.csv','r'); 
    while ($data = fgetcsv($file)) { //每次读取CSV里面的一行内容
    //print_r($data); //此为一个数组,要获得每一个数据,访问数组下标即可
    $goods_list[] = $data;
     }
    //print_r($goods_list);
    
    /* foreach ($goods_list as $arr){
        if ($arr[0]!=""){
            echo $arr[0]."<br>";
        }
    } */
     echo $goods_list[2][0];
    
     fclose($file);
    ?> 

    读取csv文件的某一行数据

    <?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);
    ?> 

    读取csv文件制定行数(行区间)

    <?php
    
    function get_file_line( $file_name, $line_star,  $line_end){
        $n = 0;
        $handle = fopen($file_name,"r");
        if ($handle) {
            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);  //从第11行到第20行
    foreach ($aa as $bb){
        echo $bb."<br>";
    }
    ?> 

    另外从网上找的两种方法(没测试,不知道好不好使)

    <?
    
    $handle=fopen("1.csv","r");
    
    while(!feof($handle)){
    
    $buffer=fgetss($handle,2048);
    
    $data=explode(",",$buffer);
    
    $num=count($data);
    
    for($i=0;$i<$num;$i++){
    
    print_r($data);
    
    }
    
    }
    
    ?>
    <?
    
    $handle=fopen("1.csv","r");
    
    $row=1;
    
    while($data=fgetcsv($handle,1000,",")){
    
    $num=count($data);
    
    for($i=0;$i<$num;$i++){
    
    echo $data[$i];
    
    }
    
    $row++;
    
    }
    
    ?>
  • 相关阅读:
    3.18日
    线程的面试题
    关于instanceof测试遇到的问题
    spring
    自动登录代码
    Filter
    多态
    基于HTML,css,jQuery,JavaScript,MySQL搭建博客系统
    基于bootstrap+MySQL搭建动态网站
    基于bootstrap_网站汇总页面
  • 原文地址:https://www.cnblogs.com/xcxc/p/2672956.html
Copyright © 2011-2022 走看看