简体   繁体   中英

select some csv values to export in html table with php

I've copied this php:

<?Php 
echo "<html><body><table border=1>";
$f = fopen("datos.csv", "r");
$fr = fread($f, filesize("datos.csv"));
fclose($f);
$lines = array();
$lines = explode("\r\n",$fr); // IMPORTANT the delimiter here just the "new line" \r\n, use what     u need instead of... 

for($i=0;$i<count($lines);$i++) {
    echo "<tr>";
    $cells = array(); 
    $cells = explode(",",$lines[$i]); // use the cell/row delimiter what u need!
    for($k=0;$k<count($cells);$k++) {
        echo "<td>".$cells[$k]."</td>";
    }
    // for k end
    echo "</tr>";
}
// for i end
echo "</table></body></html>";
?> 

This code generates the html table. I have a csv with one column with diferent values separated with comma, and I want only some values. The question is the loop with the variable $k to catch only value2, value4, value7 ,... I appreciate some help, I'm learning php but I start in advanced mode :-( and I search this site but don't find it.

Its always dangerous to read a whole file into memory, eventually you will find a file that is large enough to blow the script up because it is Too Large to read into memory.

Use fgetcsv() instead in this situation. This reads one line at a time from your csv file, into an array, all you then have to do is pick the occurances (columns) you actually want to process.

if (($handle = fopen("datos.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 2000, ",")) !== FALSE) {

        // pick the columns you are interested in
        // remember arrays start at index 0
        echo sprintf('The bits I am interested in %s, %s, %s<br>',
                        $data[2], $data[4], $data[7]);
    }
    fclose($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