PHP dynamically create CSV: Skip the first line of a CSV file

后端 未结 8 1405
暖寄归人
暖寄归人 2020-12-05 13:19

I am trying to import a CSV file. Due to the program we use, the first row is basically all headers that I would like to skip since I\'ve already put my own headers in via

8条回答
  •  Happy的楠姐
    2020-12-05 13:48

    use this code

    // mysql hostname
    $hostname = 'localhost';
    // mysql username
    $username = 'root';
    // mysql password
    $password = '';
    
    if (isset($_FILES['file']))
    {   
    
    // get the csv file and open it up
    $file = $_FILES['file']['tmp_name'];
    //$handle is a valid file pointer to a file successfully opened by fopen(), popen(), or fsockopen(). 
    $handle = fopen($file, "r"); 
        try { 
        // Database Connection using PDO
        $dbh = new PDO("mysql:host=$hostname;dbname=clasdb", $username, $password);
        // prepare for insertion
        $STM = $dbh->prepare('INSERT INTO statstrackertemp (ServerName, HiMemUti, AvgMemUti, HiCpuUti, AvgCpuUti, HiIOPerSec, AvgIOPerSec, HiDiskUsage, AvgDsikUsage) VALUES (?, ?, ?, ?, ?,?, ?, ?, ? )');
    
    
    
            if ($handle !== FALSE) 
            {
                // fgets() Gets a line from file pointer and read the first line from $handle and ignore it.   
                fgets($handle);
                // created loop here
                while (($data = fgetcsv($handle, 1000, ',')) !== FALSE)
                {
                $STM->execute($data);
                }       
    
                fclose($handle);
    
            }
    
        } 
        catch(PDOException $e)
        {
        die($e->getMessage());
        }
    
    echo 'Data imported'; 
    
    }
    else 
    {
    echo 'Could not import Data';
    }
    
    ?>
    

提交回复
热议问题