如何在PHP中从csv文件中提取数据

我有一个csv文件,看起来像这样

$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 commas" ...有没有什么优雅的方式来做到这一点?

你可以使用fgetcsv解析一个CSV文件,而不用担心自己解析它。

PHP手册中的示例:

 $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>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; } } fclose($handle); } 

除了Matt的建议之外 ,您还可以使用SplFileObject读取文件:

 $file = new SplFileObject("data.csv"); $file->setFlags(SplFileObject::READ_CSV); $file->setCsvControl(',', '"', '\\'); // this is the default anyway though foreach ($file as $row) { list ($fruit, $quantity) = $row; // Do something with values } 

来源: http : //de.php.net/manual/en/splfileobject.setcsvcontrol.php

这里也是一个简单的方法来获取读取CSV文件。

 $ sfp = fopen('/ path / to / source.csv','r'); 
 $ dfp = fopen('/ path / to / destination.csv','w'); 
 while($ row = fgetcsv($ sfp,10000,“,”,“”)){ 
  $ goodstuff =“”; 
  $ goodstuff = str_replace(“|”,“,”,$ row [2]); 
  $ goodstuff。=“\ n”; 
  FWRITE($ DFP,$ goodstuff); 
 } 
 FCLOSE($ SFP); 
 FCLOSE($ DFP);

WebIt4Me / reader提供了一个读取或搜索CSV文件的工具

假设你为同样的事情创建了一个函数,那么它应该看起来像

 function csvtoarray($filename='', $delimiter){ if(!file_exists($filename) || !is_readable($filename)) return FALSE; $header = NULL; $data = array(); if (($handle = fopen($filename, 'r')) !== FALSE ) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { if(!$header){ $header = $row; }else{ $data[] = array_combine($header, $row); } } fclose($handle); } if(file_exists($filename)) @unlink($filename); return $data; } $data = csvtoarray('file.csv', ','); print_r($data); 

您可以使用以下功能读取数据。

  function readCSV() { $csv = array_map('str_getcsv', file('data.csv')); array_shift($csv); //remove headers } 

http://www.pearlbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/

你可以使用像https://github.com/htmlburger/carbon-csv这样的列映射:;

 $csv = new \Carbon_CSV\CsvFile('path-to-file/filename.csv'); $csv->set_column_names([ 0 => 'first_name', 1 => 'last_name', 2 => 'company_name', 3 => 'address', ]); foreach ($csv as $row) { print_r($row); } 

下面的代码的结果是这样的:

 Array ( [0] => Array ( [first_name] => John [last_name] => Doe [company_name] => Simple Company Name [address] => Street Name, 1234, City Name, Country Name ) [1] => Array ( [first_name] => Jane [last_name] => Doe [company_name] => Nice Company Name [address] => Street Name, 5678, City Name, Country Name ) ) 

另一个图书馆,做同样的事情(和更多)是http://csv.thephpleague.com/9.0/reader/