簡體   English   中英

在php中讀取.csv文件

[英]Reading .csv file in php

我想在PHP中讀取.csv文件並將其內容放入數據庫中。 我寫了以下代碼:

$row = 1;
$file = fopen("qryWebsite.csv", "r");
while (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
    $num = count($data);
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "\n";}}
fclose($file);

我沒有收到任何錯誤,但它沒有顯示我的結果。

我使用parseCSV類從csv文件中讀取數據。 它可以在讀取csv文件時提供更大的靈活性。

這沒有經過測試......但是這樣的事情應該可以解決問題:

$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."')
            ");
        }
    }
}
$fp = fopen('ReadMe.csv','r') or die("can't open file");
print "<table>\n";
while($csv_line = fgetcsv($fp,1024)) {
    print '<tr>';
    for ($i = 0, $j = count($csv_line); $i < $j; $i++) {
        print '<td>'.$csv_line[$i].'</td>';
    }
    print "</tr>\n";
}
print '</table>';
fclose($fp) or die("can't close file");

更多細節

試試這個....

在PHP中,能夠讀取CSV文件並訪問其數據通常很有用。 這就是fgetcsv()函數派上用場的地方,它將讀取CSV文件的每一行並將每個值分配到ARRAY中。 您可以在函數中定義分隔符以及fgetcsv()的 PHP文檔以獲取更多選項和示例。

  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>';

一個使用str_getcsv將CSV文件解析為數組的線程

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

要構建一個數據庫查詢,它將所有值一次導入數據庫:

$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 ) );

這將使用問號占位符構建一個准備好的語句,如:

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

和變量$values將是保存語句值的一維數組。 這里需要注意的一點是,csv文件應包含少於65,536個條目(最大占位符數)。

一個用於將CSV文件解析為數組的線程

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

您可以嘗試以下代碼。 它對我來說很完美。 我發表評論使其更容易理解。 您可以參考此代碼。

<?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);

如果你正在使用作曲家包管理器 ,你也可以依賴於league/csv

根據該文件

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM