fgetcsv skip rows?

Discussion in 'PHP' started by sensoryaddict, Sep 1, 2010.

  1. #1
    I am new to php so I sort of pieced this together with help from google and digialpoint.

    The script is working great, however I need to skip useless lines.

    The first 2 rows are header rows. I need to skip this. Also, there is a row that comes 2 rows after the last row "(x rows affected)". I also want to skip that.

    Can someone help append the code.

    // import csv into db tables

    //parse csv data

    $filename = $file ;

    $handle = fopen("$filename", "r");

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)

    {


    // convert date string

    $timestamp = strtotime($data[6]);

    $newdate = date('Y-m-d',$timestamp);

    // insert into table

    $import="INSERT into table1(date,value) values('$newdate','$data[3]')";

    mysql_query($import) or die(mysql_error());

    }



    fclose($handle);
     
    sensoryaddict, Sep 1, 2010 IP
  2. jpratama

    jpratama Member

    Messages:
    31
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    43
    #2
    There are dozen ways to do it, and I give one of the example below. Just grab the principle which I commented.
    $i = 0;
         while (($data = fgetcsv($handle, 1000, ",")) !== FALSE)
    
         {
    
    // Skip the line that has "x rows affected"
    foreach($data as $datum) {
      if($datum == "x rows affected") {
        $skip = 1;
      }
    }
    
    // Will skip the first 2 rows
    if($i != 0 || $i != 1 || $skip == 1) {
    
    // convert date string
    	
    	$timestamp = strtotime($data[6]);
    	
    	$newdate = date('Y-m-d',$timestamp);
    	
    // insert into table	
    
           $import="INSERT into table1(date,value) values('$newdate','$data[3]')";
    
           mysql_query($import) or die(mysql_error());
    }
    	   $i++;
    	 }
    
      
    
         fclose($handle);
    PHP:
     
    jpratama, Sep 2, 2010 IP
  3. sensoryaddict

    sensoryaddict Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    This did not work for me.

    I am getting the same output.
     
    sensoryaddict, Sep 2, 2010 IP
  4. sensoryaddict

    sensoryaddict Peon

    Messages:
    33
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    anybody know how to do this?
     
    sensoryaddict, Sep 6, 2010 IP