在php中读取.csv文件

发布于 2024-10-27 03:21:25 字数 326 浏览 3 评论 0原文

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

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

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 (($data = fgetcsv($file, 8000, ",")) !== FALSE) {
    $num = count($data);
    $row++;
    for ($c=0; $c < $num; $c++) {
        echo $data[$c] . "\n";}}
fclose($file);

I do not get any error but it does not show me result.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

长不大的小祸害 2024-11-03 03:21:25

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

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

南汐寒笙箫 2024-11-03 03:21:25

这还没有经过测试...但是类似这样的事情应该可以解决问题:

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

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."')
            ");
        }
    }
}
匿名的好友 2024-11-03 03:21:25
$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");

更多详细信息

$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

冷…雨湿花 2024-11-03 03:21:25

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

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 ).

撩心不撩汉 2024-11-03 03:21:25

如果您使用 composer 包管理器,您还可以依赖 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

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
悲凉≈ 2024-11-03 03:21:25

试试这个......

在 PHP 中,能够读取 CSV 文件并访问其数据通常很有用。这就是 fgetcsv() 函数派上用场的地方,它将读取 CSV 文件的每一行并将每个值分配到一个数组中。您可以在函数中定义分隔符,也可以参见 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>';

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>';
淡莣 2024-11-03 03:21:25

您可以尝试下面的代码。它非常适合我。我有评论以使其更容易理解。您可以参考这段代码。

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

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);
假扮的天使 2024-11-03 03:21:25

试试这个....

$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"
  }
  ...
}

Try this....

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

Result

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"
  }
  ...
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文