<p>最近做了相关的功能,从CSV格式的文件中读取数据,然后进行操作,下面用实例代码记录下。这里跟大家跟大家分享三种比较实用的方法:</p><pre class="brush:php;toolbar:false">$file = "/public/upload/test.csv"; $handle = fopen($file, 'r') or die("open file failure!");</pre><p><strong>方法一:指定行(区间)</strong></p><pre class="brush:php;toolbar:false">if ( $handle ) { $n = 0; while ( !feof($handle) ) { ++$n; $out = mb_convert_encoding(fgets($handle, 4096), 'utf-8', 'GBK,UTF-8,ASCII'); $start <= $n && $data[$n] = $out; if ( $end == $n ) break; } fclose($handle); }</pre><p><strong>方法二:按照行来读</strong></p><pre class="brush:php;toolbar:false">$line = 1000; $n = 0; if ($file) { while (!feof($file)) { ++$n; $data[] = mb_convert_encoding(fgets($file, 4096), 'utf-8', 'GBK,UTF-8,ASCII'); if($line==$n) break; } fclose($file); }</pre><p><strong>方法三:按照数据条数</strong><span style="color: rgb(255, 0, 0);">(推荐使用)</span></p><pre class="brush:php;toolbar:false">while(!feof($handle) ) { $result = fgetcsv($handle, 4096); if ( is_array($result) ) { foreach ( $result as $k => $v ) { $result[$k] = mb_convert_encoding($v, 'utf-8', 'GBK,UTF-8,ASCII'); } } $data[] = $result; } fclose($handle);</pre><p>上面三种方式,作者都认真测试过可以使用,测试后第三种方法效率还是比较高的,读取速度也比较快,因此推荐给大家。</p><p>以上就是关于“PHP读取CSV文件内容,PHP导入CSV文件数据”的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流。</p>