简体   繁体   中英

How to fetch specific column from a file?

I am trying to fetch a specific column from a file by using 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:

$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.

// 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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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