如何在PHP中从csv文件中提取数据 [英] How to extract data from csv file in PHP

查看:42
本文介绍了如何在PHP中从csv文件中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 csv 文件

I have a csv file which looks like this

$lines[0] = "text, with commas", "another text", 123, "text",5;
$lines[1] = "some without commas", "another text", 123, "text";
$lines[2] = "some text with commas or no",, 123, "text";

我想要一张桌子:

$t[0] = array("text, with commas", "another text", "123", "text","5");
$t[1] = array("some without commas", "another text", "123", "text");
$t[2] = array("some text, with comma,s or no", NULL , "123", "text");

如果我使用 split($lines[0],",") 我会得到 "text" ,"with逗号" ...有什么优雅的方法吗?

If I use split($lines[0],",") I'll get "text" ,"with commas" ... Is there any elegant way to do it?

推荐答案

您可以使用 fgetcsv 解析 CSV 文件,而不必担心自己解析.

You can use fgetcsv to parse a CSV file without having to worry about parsing it yourself.

PHP 手册中的示例:

Example from PHP Manual:

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>
";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />
";
        }
    }
    fclose($handle);
}

这篇关于如何在PHP中从csv文件中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆