简体   繁体   English

如何从文件中获取特定的列?

[英]How to fetch specific column from a file?

I am trying to fetch a specific column from a file by using PHP. 我正在尝试通过使用PHP从文件中获取特定列。 but so far I got all of it, have no idea how to do this, I can not find any information online so if anyone could help me about this , I will be very appreciated. 但到目前为止,我已经掌握了所有信息,不知道如何执行此操作,我无法在网上找到任何信息,因此,如果有人可以帮助我,我将非常感激。 The data in file is like blow: 文件中的数据就像一击:

20110101,1110.0 
20110102,1100.0 
20110103,50.0 
20110104,6355.0 
........

I just want to fetch the second column, here is my PHP code: 我只想获取第二列,这是我的PHP代码:

$file_handle = fopen("file_name", "r");
    while (!feof($file_handle)) {
        $line = fgets($file_handle);
        echo $line."<br/>";
}
fclose($file_handle);

Have you tried this (which actually does what you want, without refactoring) : 您是否尝试过此方法(实际上是在不重构的情况下完成了您想要的操作):

$file_handle = fopen("file_name", "r");
while (!feof($file_handle)) {
   $line = fgets($file_handle);
   $cols = explode(',', $line);
   echo $cols[1]."<br/>";
}
fclose($file_handle);

?? ??

As Vlad says, use fgetcsv. 如Vlad所说,请使用fgetcsv。

// adapted from PHP example
$max_row_len = 1000;
if (($file_handle = fopen("file_name", "r")) !== FALSE) {
    while (($data = fgetcsv($file_handle, $max_row_len, ",")) !== FALSE) {
        echo $data[1]."<br/>";
    }
    fclose($file_handle);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM