在php中阅读.csv文件

biswetbf  于 12个月前  发布在  PHP
关注(0)|答案(8)|浏览(98)

我想在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);

我没有得到任何错误,但它没有显示我的结果。

9nvpjoqh

9nvpjoqh1#

我正在使用parseCSV类从csv文件中读取数据。它可以在阅读csv文件时给予更大的灵活性。

lf5gs5x2

lf5gs5x22#

这是没有测试…但像这样的东西应该能解决问题

$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."')
            ");
        }
    }
}
i34xakig

i34xakig3#

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

More Details

mxg2im7a

mxg2im7a4#

一个使用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个条目(占位符的最大数量)。

stszievb

stszievb5#

试试这个...
在PHP中,能够读取CSV文件并访问其数据通常很有用。这就是fgetcsv()函数派上用场的地方,它将读取CSV文件的每一行,并将每个值赋给一个ARRAY。你也可以在函数中定义分隔符,更多的选项和例子请参见PHP文档中的fgetcsv()

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

7d7tgy0s6#

如果您使用的是composer package manager,则还可以依赖league/csv
根据他们的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
lxkprmvk

lxkprmvk7#

你可以试试下面的代码。对我来说太完美了。我有一个评论,使它更容易理解。你可以从这段代码中得到参考。

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

jdgnovmf8#

试试这个...

$cel_values = [];`
$column_keys = [];
if (($handle = fopen("imagenes_1.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $values = [];
        $num = count($data);
        $row++;
        for ($c = 0; $c < $num; $c++) {
            if($row == 1){
                $column_keys[] = $data[$c]; 
            }else{
                $values[] = $data[$c];
            }
        }
        if($row != 1){
            $cel_values[] = (object) array_combine($column_keys, $values);
        }
    }
    fclose($handle);
}

var_dump($cel_values);
exit;

结果

array(20) {
  [0]=>
  object(stdClass)#1 (3) {
    ["id"]=>
    string(10) "0000000000"
    ["date"]=>
    string(26) "2023-02-24 15:46:44.000000"
    ["name"]=>
    string(26) "1-16772509601764653725.png"
  }
  ...
}

相关问题