0

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.

1
  • 2
    Note, don't use explode() to break up a CSV file, it won't handle quotes and escaped characters correctly. Use fgetcsv() instead. Commented Sep 2, 2020 at 16:53

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

"eventually you will find a file that is large enough to blow the script up" ... been there done that! Very good note about how fgetcsv is more efficient in this regard.
thanks, you do it. now I try to put in a html table, It seems easy but there is a lot of variables, I need a lot of hours of programming to do something

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.