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

问题描述

可有人请提供一个code。使用fgetcsv创建从CSV文件的数组?

我用下面的code创建从一个简单的CSV文件的数组,但是当我的领域之一,拥有多个逗号不正确的工作 - 比如地址

  $线=文件(CSV Address.csv');的foreach($线为$的数据)
{
列表($名称[],$地址[],$地位[])
=爆炸(,,$数据);
}

*另外,str_getcsv不是由我的托管服务的支持。

以上code不与下面的CSV文件工作的例子。第一列名,第二列是地址,第三列是婚姻状况。

 斯科特L.阿兰达,123大街,马里兰州贝塞斯达20816,单
托德D.史密斯,987榆树街,亚历山大,弗吉尼亚州22301,单
爱德华·草,123大街,马里兰州贝塞斯达20816,已婚
亚伦G.弗朗茨,987榆树街,亚历山大,弗吉尼亚州22301,已婚
瑞安五特纳,123大街,马里兰州贝塞斯达20816,单


解决方案

就像你在你的标题,是要走的路。这是pretty织补容易使用。

  $文件=的fopen('myCSVFile.csv','R');
而(($行= fgetcsv($文件))!== FALSE){
  // $线是CSV元件的阵列
  的print_r($线);
}
FCLOSE($文件);

您会希望把更多的错误检查中存在的情况下, fopen()函数失败,但这部作品读一行CSV文件一行并解析行成阵列

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

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);
}

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

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
解决方案

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);

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文件数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 06:55