2013-04-25 26 views
0

所以我有一個表單和解析器成功上傳一個csv文件並解析它,但我只想抓住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

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++; 
    } 
+0

運作良好,加雷你搖滾的人! – Squirtle 2013-04-25 05:46:06