猿问

如何从PHP中的CSV文件中提取数据

如何从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" ...有什么优雅的方法吗?


凤凰求蛊
浏览 742回答 3
3回答

qq_花开花谢_0

你可以用fgetcsv解析CSV文件而不必担心自己解析它。PHP手册中的示例:$row&nbsp;=&nbsp;1;if&nbsp;(($handle&nbsp;=&nbsp;fopen("test.csv",&nbsp;"r"))&nbsp;!==&nbsp;FALSE)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;while&nbsp;(($data&nbsp;=&nbsp;fgetcsv($handle,&nbsp;1000,&nbsp;","))&nbsp;!==&nbsp;FALSE)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$num&nbsp;=&nbsp;count($data); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;"<p>&nbsp;$num&nbsp;fields&nbsp;in&nbsp;line&nbsp;$row:&nbsp;<br&nbsp;/></p>\n"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$row++; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;for&nbsp;($c=0;&nbsp;$c&nbsp;<&nbsp;$num;&nbsp;$c++)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;$data[$c]&nbsp;.&nbsp;"<br&nbsp;/>\n"; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;fclose($handle);}

白衣染霜花

这里还有一个读取CSV文件的简单方法。$sfp&nbsp;=&nbsp;fopen('/path/to/source.csv','r');&nbsp; $dfp&nbsp;=&nbsp;fopen('/path/to/destination.csv','w');&nbsp; while&nbsp;($row&nbsp;=&nbsp;fgetcsv($sfp,10000,",",""))&nbsp;{&nbsp; &nbsp;$goodstuff&nbsp;=&nbsp;"";&nbsp; &nbsp;$goodstuff&nbsp;=&nbsp;str_replace("¦",",",$row[2]);&nbsp; &nbsp;$goodstuff&nbsp;.=&nbsp;"\n";&nbsp; &nbsp;fwrite($dfp,$goodstuff);&nbsp; }&nbsp; fclose($sfp);&nbsp; fclose($dfp);
随时随地看视频慕课网APP
我要回答