2015-04-12 114 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); 
     } 
    } 
} 

?>