如何使用 PHP 和 fgetcsv 函数从 CSV 文件创建数组 [英] How to create an array from a CSV file using PHP and the fgetcsv function

查看:36
本文介绍了如何使用 PHP 和 fgetcsv 函数从 CSV 文件创建数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以提供使用 fgetcsv 从 CSV 文件创建数组的代码吗?

Can someone kindly provide a code to create an array from a CSV file using fgetcsv?

我使用以下代码从一个简单的 CSV 文件创建了一个数组,但是当我的一个字段有多个逗号时它无法正常工作 - 例如地址.

I've used the following code to create an array from a simple CSV file, but it doesn't work right when one of my fields has multiple commas - such as addresses.

$lines =file('CSV Address.csv');

foreach($lines as $data)
{
list($name[],$address[],$status[])
= explode(',',$data);
}

*此外,我的托管服务不支持 str_getcsv.

*Also, str_getcsv is not supported by my hosting service.

以上代码不适用于以下 CSV 文件示例.第一列是姓名,第二列是地址,第三列是婚姻状况.

The above code doesn't work with the following CSV file example. First column is name, second column is address, third column is marital status.

Scott L. Aranda,"123 Main Street, Bethesda, Maryland 20816",Single
Todd D. Smith,"987 Elm Street, Alexandria, Virginia 22301",Single
Edward M. Grass,"123 Main Street, Bethesda, Maryland 20816",Married
Aaron G. Frantz,"987 Elm Street, Alexandria, Virginia 22301",Married
Ryan V. Turner,"123 Main Street, Bethesda, Maryland 20816",Single

推荐答案

就像你在标题中所说的,fgetcsv 是要走的路.它非常易于使用.

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

如果 fopen() 失败,您需要在其中进行更多错误检查,但这可以逐行读取 CSV 文件并将该行解析为数组.

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

这篇关于如何使用 PHP 和 fgetcsv 函数从 CSV 文件创建数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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