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

查看:145
本文介绍了如何使用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天全站免登陆