在php中读取.csv文件
我想用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
我正在使用 parseCSV 类从 csv 文件读取数据。它可以在读取 csv 文件时提供更大的灵活性。
I am using parseCSV class to read data from csv files. It can give more flexibility in reading csv file.
这还没有经过测试...但是类似这样的事情应该可以解决问题:
this is not tested... but something like this should do the trick:
更多详细信息
More Details
使用 str_getcsv 将 CSV 文件解析为数组的一个衬垫。
构建一个将所有值一次性导入数据库的数据库查询:
这将构建一个带有问号占位符的准备好的语句,例如:
,变量
$values
将是保存值的一维数组对于声明。这里需要注意的是,csv 文件应包含少于 65,536 个条目(占位符的最大数量)。One liner to parse a CSV file into an array by using str_getcsv.
To build a database query that will import all the values into database at once:
This will build a prepared statement with question mark placeholders, like:
, 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 ).如果您使用 composer 包管理器,您还可以依赖
league/csv
根据他们的文档:
If you're using the composer package manager, you can also rely on
league/csv
According to theire documentation:
试试这个......
在 PHP 中,能够读取 CSV 文件并访问其数据通常很有用。这就是 fgetcsv() 函数派上用场的地方,它将读取 CSV 文件的每一行并将每个值分配到一个数组中。您可以在函数中定义分隔符,也可以参见 PHP 文档 fgetcsv() 了解更多选项和示例。
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.
您可以尝试下面的代码。它非常适合我。我有评论以使其更容易理解。您可以参考这段代码。
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.
试试这个....
结果
Try this....
Result