我有如下csv文件中的数据
Mr,Vinay,H S,应用工程师,vinay.hs@springpeople.com,99005809800,是的先生,Mahammad侯赛因,应用工程师,vinay.hs@springpeople.com, 99005809800,是的
我想在每个数组中存储每一行。告诉我怎么做
我不理解每个数组中的每一行。
使用fgetcsv()函数读取CSV文件php.
一个例子<?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);
}
?>
或如果你想将它们存储在数组中,你可以使用
$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
}
假设CSV是一个文件(如果不是,让CSV匹配$csv
,它本质上是由单独的行分解的文件),这里有一个非常简单的方法:
$csv = file('mycsv.csv'); $result = array();
//iterate the lines
foreach ($csv as $line)
// I'd recommend more robust "csv-following" method though (fgetcsv maybe)
$result[] = explode(',',$result);
//show the results
print_r($result);
虽然fgetcsv
可能是一个更安全的赌注(正如其他人提到的)(参见文档)。
进一步扩展您的评论:
//iterate the lines
foreach ($csv as $line)
// I'd recommend more robust "csv-following" method though (fgetcsv maybe)
$result[] = explode(',',$result);
可以成为:
//iterate the lines
foreach ($csv as $line)
// combine the current results with the new results
$result = array_marge($result,$line);
或者,如果顺序很重要:
//iterate the lines
foreach ($csv as $line)
// add each result on to the end of the result array
foreach($line as $val)
// add each value
$result[] = $val;
您可以使用fgetcsv():
$data = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while(($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = $row;
}
}