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

不言
Release: 2023-04-04 17:22:01
forward
3303 people have browsed it

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');
Copy after login

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!

Related labels:
php
source:segmentfault.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template