所以我有一个表单和解析器,它成功上传了一个csv文件并解析它,但我想只抓取csv文件中的列标题。我怎么只抓住所有列标题的第一行?
function ShowForm()
{
print"<form method='post' action='$_SERVER[PHP_SELF]' enctype='multipart/form-data'>\n";
print"<p>enter csv file:\n".
"<input type='file' name ='csv' value=''/>\n"."</p>".
"<p><input type='submit' name ='submit' />".
"</p>".
"</form>";
}
//////////////////////////////////////////////////////////////////////////////////
function Processform()
{
$csv = array();
// check there are no errors
if($_FILES['csv']['error'] == 0){
$name = $_FILES['csv']['name'];
$ext = strtolower(end(explode('.', $_FILES['csv']['name'])));
$type = $_FILES['csv']['type'];
$tmpName = $_FILES['csv']['tmp_name'];
print "name : $name<br >";
print "extenstion : $ext<br >";
print "type : $type<br >";
print "name : $tmpName<br >";
if($ext === 'csv'){
if(($handle = fopen($tmpName, 'r')) !== FALSE) {
// necessary if a large csv file
set_time_limit(0);
$row = 0;
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$num = count($data);
// get the values from the csv
$csv[$row]['row1'] = $data[0];
$csv[$row]['row2'] = $data[1];
// inc the row
$row++;
}
fclose($handle);
}
}
}
}
答案 0 :(得分:0)
fgetcsv
方法从CSV文件中提取一行,因此要获取第一行,只调用一次:
if(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// handle first row
}
$row = 1;
// Now handle all the rest
while(($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
// number of fields in the csv
$num = count($data);
// get the values from the csv
$csv[$row]['row1'] = $data[0];
$csv[$row]['row2'] = $data[1];
// inc the row
$row++;
}