Reading .csv file in php

前端 未结 8 933
面向向阳花
面向向阳花 2020-12-16 15:12

I want to read .csv file in PHP and put its contents into the database. I wrote the following code:

$row = 1;
$file = fopen(\"qryWebsite.csv\", \"r\");
while         


        
相关标签:
8条回答
  • 2020-12-16 15:23

    I am using parseCSV class to read data from csv files. It can give more flexibility in reading csv file.

    0 讨论(0)
  • 2020-12-16 15:24

    If you're using the composer package manager, you can also rely on league/csv

    According to theire documentation:

    use League\Csv\Reader;
    
    //load the CSV document from a file path
    $csv = Reader::createFromPath('/path/to/your/csv/file.csv', 'r');
    $csv->setHeaderOffset(0);
    
    $header = $csv->getHeader(); //returns the CSV header record
    $records = $csv->getRecords(); //returns all the CSV records as an Iterator object
    
    0 讨论(0)
  • 2020-12-16 15:29

    You can try the below code. It works perfect for me. I have comment to make it more understandable. You can take reference from this code.

    <?php
    
    //display error message if any
    ini_set('display_startup_errors',1);
    ini_set('display_errors',1);
    error_reporting(-1);
    
    //openup connection to database
    include('dbconnection.php');
    
    //open csv file
    if (($handle = fopen("files/cities.csv", "r")) !== FALSE) {
    
        $flag = true;
        $id=1;
    
        //fetch data from each row
        while (($data = fgetcsv($handle, ",")) !== FALSE) {
            if ($flag) {
                $flag = false;
                continue;
            }
    
            //get data from each column
            $city_id      = $data[0];
            $country_name = $data[1];
            $city_name    = $data[2];
            $state_code   = $data[3];
    
            //query to insert to database
            $sql = "INSERT IGNORE INTO `DB_Name`.`cities` 
                    (`id`,`city_id`, country_name`, `city_name`,`state_code`)
                    VALUES 
                    ('$id','$city_id','$country_name','$city_name','$state_code')";
    
            echo $sql;
    
            //execute the insertion query
            $retval = mysql_query($sql, $conn);
    
            if($retval == false )
            {
              die('Could not enter data: ' . mysql_error());
            }
    
            echo "<p style='color: green;'>Entered data having id = " .$id. " successfully</p><br>";
            $id++;
        }
    
        echo "<br><p style='color: orange;'>Congratulation all data successfully inserted</p>";
    
        fclose($handle);
    }
    
    //close the connection
    mysql_close($conn);
    
    0 讨论(0)
  • 2020-12-16 15:30

    One liner to parse a CSV file into an array by using str_getcsv.

    $csv = array_map( 'str_getcsv', file( 'qryWebsite.csv' ) );
    

    To build a database query that will import all the values into database at once:

    $query = 
        "INSERT INTO tbl_name (a,b,c) VALUES " .
        implode( ',', array_map( function( $params ) use ( &$values ) {
            $values = array_merge( (array) $values, $params );
            return '(' . implode( ',', array_fill( 0, count( $params ), '?' ) ) . ')';
        }, $csv ) );
    

    This will build a prepared statement with question mark placeholders, like:

    INSERT INTO tbl_name (a,b,c) VALUES (?,?,?),(?,?,?),(?,?,?),(?,?,?)
    

    , and variable $values will be one-dimensional array that holds values for the statement. One caveat here is that csv file should contain less than 65,536 entries ( maximum number of placeholders ).

    0 讨论(0)
  • 2020-12-16 15:31

    Try this....

    In PHP it is often useful to be able to read a CSV file and access it’s data. That is where the fgetcsv() function comes in handy, it will read each line of a CSV file and assign each value into an ARRAY. You can define the separator in the function as well see PHP docs for fgetcsv() for more options and examples.

      function readCSV($csvFile){
            $file_handle = fopen($csvFile, 'r');
            while (!feof($file_handle) ) {
                $line_of_text[] = fgetcsv($file_handle, 1024);
            }
            fclose($file_handle);
            return $line_of_text;
        }
    
    
        // Set path to CSV file
        $csvFile = 'test.csv';
    
        $csv = readCSV($csvFile);
        echo '<pre>';
        print_r($csv);
        echo '</pre>';
    
    0 讨论(0)
  • 2020-12-16 15:32

    this is not tested... but something like this should do the trick:

    $row = 1;
    if (($handle = fopen("xxxxxxxxx.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            echo "<p> $num fields in line $row: <br /></p>\n";   
            $row++;
            for ($c=0; $c < $num; $c++) {
                $blackpowder = $data;
                $dynamit = implode(";", $blackpowder);
                $pieces = explode(";", $dynamit);
                $col1 = $pieces[0];
                $col2 = $pieces[1];
                $col3 = $pieces[2];
                $col4 = $pieces[3];
                $col5 = $pieces[5];
                mysql_query("
                    INSERT INTO `xxxxxx` 
                        (`xxx`,`xxx`,`xxx`,`xxxx`,`xxx`) 
                    VALUES 
                        ('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."')
                ");
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题