Home  >  Article  >  Backend Development  >  Introduction to the method of reading CSV files in php (code example)

Introduction to the method of reading CSV files in php (code example)

不言
不言forward
2019-01-09 10:43:533310browse

This article brings you an introduction to the method of reading CSV files in PHP (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Recently, I have done related functions, reading data from CSV format files, and then performing operations. The following is recorded with example code.

fgetcsv

fgetcsv — Reads a line from a file pointer and parses CSV fields

If an invalid file pointer is provided, fgetcsv() returns NULL. Other errors include returning FALSE when end-of-file is encountered.

This function is more critical. You can see that its function is to read and parse CSV fields. There are not too many parameters used this time. If necessary, please refer to the link below for your own reference.

Example

The CSV file example is as follows

Introduction to the method of reading CSV files in php (code example)

##The example code is as follows

<?php function getFileData($file)
{
    if (!is_file($file)) {
        exit(&#39;没有文件&#39;);
    }
    $handle = fopen($file, &#39;r&#39;);
    if (!$handle) {
        exit(&#39;读取文件失败&#39;);
    }
    while (($data = fgetcsv($handle)) !== false) {
        // 下面这行代码可以解决中文字符乱码问题
        // $data[0] = iconv(&#39;gbk&#39;, &#39;utf-8&#39;, $data[0]);
        // 跳过第一行标题
        if ($data[0] == &#39;name&#39;) {
            continue;
        }
        // data 为每行的数据,这里转换为一维数组
        print_r($data);// Array ( [0] => tom [1] => 12 )
    }
    fclose($handle);
}
getFileData('./01.csv');

The above is the detailed content of Introduction to the method of reading CSV files in php (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete