Goncalo Feliciano
Goncalo Feliciano

Reputation: 111

Read CSV file in php

PHP file

$teste =  fopen("teste.csv", "r");

print "<table border=\"2\">";

while (!feof($teste) ) {

$line_of_text = fgetcsv($teste);

print "<tr>
    <td>$line_of_text[0]</td>
    <td>$line_of_text[2]</td>
    <td>$line_of_text[3]</td>
    <td>$line_of_text[4]</td>
    <td>$line_of_text[5]</td>
    <td>$line_of_text[6]</td>
    <td>$line_of_text[7]</td>
    <td>$line_of_text[8]</td>
    <td>$line_of_text[9]</td>
     <td>$line_of_text[10]</td>
    <td>$line_of_text[11]</td>
  </tr>";

}

print "</table>";

fclose($teste);

CSV file

 ,912,Gold,Sat Bodegas Noroeste de La Palma,Vega Norte Albillo Criollo Seco,2013,Dry White,13,5,97,D.O.La Palma - Islas Canarias, 
 ,922,Gold,Sat Bodegas Noroeste de La Palma,Acertijo Blanco Seco,2013,Dry White,14,95,D.O.La Palma - Islas Canarias, 

im not an PHP expert but i need to create a simple system to read data form a CSV and create a table with the result

and i tried the code above, but i only get the 1st line

can anyone tell me whats wrong and how i can fix it?

Upvotes: 0

Views: 312

Answers (1)

WhiteLine
WhiteLine

Reputation: 1991

Read and print the entire contents of a CSV file

<?php

echo "<table>";
$row = 1;
if (($handle = fopen("teste.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        //echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        echo "<tr>";
        for ($c=0; $c < $num; $c++) {
            //echo $data[$c] . "<br />\n";
            echo "<td>".$data[$c]."</td>";
        }
        echo "</tr>";
    }
    fclose($handle);
}
echo "</table>";
?>

Upvotes: 2

Related Questions