user3391894
user3391894

Reputation: 9

How to get the line number per row in CSV file using PHP

I have a CSV file that can viewed in WEB using PHP and HTML table using the code below.

I want to get the line number per row of the CSV file using PHP. I am able to get the total line number using COUNT, but I don't need the total; what I need is the line number per row.

How can I get that?

Here is my Code :

<?php      
             if (($handle = fopen("bin/pdw_table.csv", "c+")) !== FALSE) 
             {

?>
        <table class="table table-hover table-striped table-bordered" id="table-data">
             <tr class="tr1">
                  <th>Field 1</th>
                  <th>Field 2</th>
                  <th>Field 3</th>
                  <th></th>
                  <th>Field 4</th>
                  <th>Field 5</th>
                  <th></th>
                  <th></th>
                  <th>Field 6</th>
                  <th>Field 7</th>
                  <th>Field 8</th>
                  <th>Field 9</th>
                  <th>Field 10</th>
                  <th>Field 11</th>
                  <th>Field 12</th>
                  <th>Field 13</th>
                  <th></th>
                  <th>Field 14</th>
                  <th>Field 15</th>
                  <th>Field 16</th>
                  <th></th>
               </tr>
 <?php
      while (($data = fgetcsv($handle, 10000, ',')) !== FALSE) {
           $num = count($data);
           $row++;
 ?>
              <tr <?php if($row==0){echo "style='font-weight:bold; background-color:#CCCCCC'";} else {echo "style='background-color:#DDDDDD'";} ?> style="background-color:#DDDDDD">
 <?php
      for ($c=0; $c < $num; $c++) 
    {
 ?>
       <td><?php echo $data[$c]; ?></td>

<?php
  }
?>
       <td><a href="#" style="cursor: pointer;">Delete</a></td>
      </tr>
<?php

      $row++;
          }
             fclose($handle);
 ?>

      <form method="post" name="add1" id="add1" action="<?php echo base_url();?>index.php/datacast_ctr/write_csv" autocomplete="off">
           <tr class="td1" id="td1" >  
               <td><input type="text" name="val1" id="val1"/></td>
               <td><input type="text" name="val2" id="val2"/></td>
               <td><input type="text" name="val3" id="val3"/></td>
               <td></td>
               <td><input type="text" name="val4" id="val4"/></td>
               <td><input type="text" name="val5" id="val5"/></td>
               <td></td>
               <td></td>
               <td><input type="text" name="val6" id="val6"/></td>
               <td><input type="text" name="val7" id="val7"/></td>
               <td><input type="text" name="val8" id="val8"/></td>
               <td><input type="text" name="val9" id="val9"/></td>
               <td><input type="text" name="val10" id="val10"/></td>
               <td><input type="text" name="val11" id="val11"/></td>
               <td><input type="text" name="val12" id="val12"/></td>
               <td><input type="text" name="val13" id="val13"/></td>
               <td></td>
               <td><input type="text" name="val14" id="val14"/></td>
               <td><input type="text" name="val15" id="val15"/> </td>
               <td><input type="text" name="val16" id="val16"/></td>
            </tr>
         </form>
     </table>
  <?php
       }
  ?>

Upvotes: 0

Views: 1884

Answers (1)

krowe
krowe

Reputation: 2270

Here is how I'd write this:

<?php

$csv_file='bin/pdw_table.csv';
$csv_form_action=base_url().'index.php/datacast_ctr/write_csv';

// If you make an array for the columns then you will be able to easily adjust them. 
// You only want this information in one place so that changes are propigated everywhere.
$cols=array(
    array('title'=>'Field 1', 'name'=>'val1', 'type'=>'text'),
    array('title'=>'Field 2', 'name'=>'val2',),
    array('title'=>'Field 3', 'name'=>'val3',),
    array(),
    array('title'=>'Field 4', 'name'=>'val4',),
    array('title'=>'Field 5', 'name'=>'val5',),
    array(),
    array(),
    array('title'=>'Field 6', 'name'=>'val6',),
    array('title'=>'Field 7', 'name'=>'val7',),
    array('title'=>'Field 8', 'name'=>'val8',),
    array('title'=>'Field 9', 'name'=>'val9',),
    array('title'=>'Field 10', 'name'=>'val10',),
    array('title'=>'Field 11', 'name'=>'val11',),
    array('title'=>'Field 12', 'name'=>'val12',),
    array('title'=>'Field 13', 'name'=>'val13',),
    array(),
    array('title'=>'Field 14', 'name'=>'val14',),
    array('title'=>'Field 15', 'name'=>'val15',),
    array('title'=>'Field 16', 'name'=>'val16',),
    array(),
);

if(filter_has_var(INPUT_GET, 'del'))
    csv_delete_record($csv_file, filter_input(INPUT_GET, 'del', FILTER_SANITIZE_NUMBER_INT));

csv_table($csv_file, $cols, true);
csv_table_form($cols, $csv_form_action);

/**
 * This function writes a table given a CSV file and a column definition.
 * 
 * Be sure that the column array is correct for the CSV file.
 * 
 * @param string $handle The CSV file name.
 * @param mixed $cols The column definition array.
 */
function csv_table($filename, $cols, $show_delete=false) {
    if(($handle=fopen($filename, "c+"))!==FALSE) {
        // This is a much better way to provide alternating table row styles for several reasons
        // This should probably be put in your CSS file instead of here though.
        echo "\n\t<style>\n".
            "\t\t.table-striped tr:nth-child(1) {background-color:#ddd}\n".
            "\t\t.table-striped tr:nth-child(2) {font-weight:bold; background-color:#ccc}\n".
            "\t\t.table-striped tr td:last-child a {cursor:pointer}\n".
            "\t</style>\n\n";
        echo "\t<table class='table table-hover table-striped table-bordered' id=table-data>\n\t\t<tr>";
        foreach($cols as $col) {
            echo '<th>';
            if(isset($col['title'])) {
                echo $col['title'];
                // We can go ahead and fill out the defaults here
                if(!isset($col['name'])) $col['name']=str_replace(' ', '-', $col['title']);
                if(!isset($col['type'])) $col['type']='text';
                if(!isset($col['id'])) $col['id']=$col['name'];
            }
        }
        echo "\n";
        $row=0;
        while(($data=fgetcsv($handle, 10000, ','))!==FALSE) {
          $row++;
          $num=count($data);
          echo "\t\t<tr>";
          for($c=0; $c<$num; $c++) echo "<td>".$data[$c];
          if($show_delete) echo "<td><a href=?del=$row>Delete</a>"; // This may need tweaking for your site
              echo "\n";      
        }
        fclose($handle);
        echo "\t</table>\n";
    }
}
/**
 * This creates a form in a table layout to match a csv_table() table.
 * 
 * @param mixed $cols The column definition array.
 * @param string $form_action where to send the form post
 */
function csv_table_form($cols, $form_action) {
    echo "\t<form method=post name=add1 id=add1 action='$form_action' autocomplete=off>\n".
        "\t\t<table class='table table-hover table-striped table-bordered' id=table-data>\n\t\t<tr>";
        "\t\t\t<tr class=td1 id=td1>\n";
    foreach($cols as $col) {
        echo "<td>";
        if(isset($col['name'])) echo "<input type=${col['type']} name=${col['name']} id=${col['id']} />";
    }
    echo "\t\t</table>\n\t</form>\n";
}
/**
 * Delete a row from a file. It is meant for CSV files but works for any file with newlines.
 * 
 * This can be improved by just opening the file once in read-write mode but that'd take a little more effort.
 * 
 * @param string $filename
 * @param int $row_number The line of the file to remove
 */
function csv_delete_record($filename, $row_number) {
    $lines=file($filename);
    if(isset($lines[$row_number])) unset($lines[$row_number]);
    $lines=implode("\n", $lines);
    if($h=fopen($filename, 'a')) {
        fputcsv($h, $lines, '-');
        fclose($h);
    }
}

Upvotes: 1

Related Questions