質問

I have been working on importing a csv file into a mysql database. Problem is my client gets the files already with some bad formatting. the rows end at 43 but the file goes down to 65078!!

When importing, the script takes forever. What can I do to make sure just the rows from 0 to 44 get imported? Here's the code i'm using.

  <table>
<?php
//fgetcsv($handle, 1024, delimiter)
$file = fopen("prices.csv", "r");
$row = 0;

    while($csv_line = fgetcsv($file,1024)) {

      if($row ==    4){
        echo "How many headers do we have: ".count($csv_line)."<tr>";

         foreach($csv_line as $header){

           if($header !== NULL){
            print "<td>$header</td>";
           }
         }
         echo "</tr>";
      } 

      if($row > 6) {

        echo '<tr>';

        for ($i = 0, $j = count($csv_line); $i < $j; $i++) {

          echo '<td>'.$csv_line[$i].'</td>';

        }

        echo "</tr>\n";

      } else {

        $row++;

      }

    } 
?>

</table>
役に立ちましたか?

解決

If the number of filled rows isn't fixed, you can use similar approach with:

if (empty($line)) { break; }

Your comment give me an idea for a better solution:

Here http://php.net/manual/en/function.fgetcsv.php appears this "A blank line in a CSV file will be returned as an array comprising a single null field" so maybe this helps:

while(($csv_line = fgetcsv($file,1024)) && $csv_line[0]) {

Will read only until finds an empty row.

他のヒント

Add a if ($row >= 44) { break; } at the bottom of the loop so it'll exit once you reach row 44.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top