2015-04-12 55 views
0

我試圖從.csv接收數據。這裏我到目前爲止的代碼是:php按列讀取csv數據

if(($handle = fopen("test.csv", "r")) !== FALSE){ 
    while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){ 
    } 
} 

但是這將所有我需要的數據放在$ data數組的第一個條目中。我需要做的是$data[1],然後從第二列中獲取所有值。我以前做過,但這次我不能這樣做。我該怎麼做?

編輯

這裏是我的.csv文件結構

| ID | Name | 
|------|----------|etc 
| 1 |Product 1 | 

這裏的文件http://imgur.com/BlaCvjo

而且隨着echo $data[1]它應該返回的截屏 '產品1'

+0

在'$ data'中,您將擁有每行的單列。所以請舉一個小輸入文件的示例,並且我現在已經在問題中包含了期望的輸出 – Rizier123

+0

@ Rizier123。我還無法使用圖像,因爲我的代表太低 – Orynuh

+0

對我來說工作正常!你有任何錯誤?你會得到什麼輸出? – Rizier123

回答

0

請具體到您的問題。無論如何,這些代碼將幫助你解決你的問題。

<?php 
$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']; 

    // check the file is a csv 
    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 
       $col_count = count($data); 

       // get the values from the csv 
       $col1 = $data[0]; 
       $col2 = $data[1]; 
       $col3 = $data[2]; 
       $col4 = $data[2];    
       // inc the row 
       $row++; 
      } 

      fclose($handle); 
     } 
    } 
} 

?>