如何将CSV文件中的值实际分割为MySQL数据库

时间:2022-09-26 13:26:24

Let's suppose I have the following line in a CSV file (I removed the header row in this example):

假设CSV文件中有以下一行(在本例中删除了头行):

"500,000",2,50,2,90000

I have a PHP script read the CSV file, break the file into individual lines, and store each line in an array called $linearray. Then, I use a foreach loop to look at each line individually.

我有一个PHP脚本读取CSV文件,将文件拆分为单独的行,并将每一行存储在一个名为$linearray的数组中。然后,我使用foreach循环逐个查看每一行。

Within the foreach loop, I break the line into separate variables using the following function:

在foreach循环中,我使用以下函数将这条线分割成独立的变量:

$line = str_replace("'","\'",$line);

From here, I insert the values into separate columns within a MySQL database. The script works. The values are inserted into a database, but I run into a problem. I want:

从这里开始,我将这些值插入到MySQL数据库中的单独列中。脚本工作。这些值被插入到数据库中,但是我遇到了一个问题。我想要:

"500,000"  |  2  |  50  |  2  |  90000

But I get this:

但我得到这个:

"500  |  000"  |  2  |  50  |  2  |  90000

The script isn't smart enough to understand it should skip commas within quotation marks. Do you know how I can alter my script to make sure I get the output I'm looking for?

这个脚本不够聪明,不能理解它应该在引号中跳过逗号。你知道我如何修改我的脚本以确保我得到我正在寻找的输出吗?

2 个解决方案

#1


2  

You can use the str_getcsv function

您可以使用str_getcsv函数

print_r(str_getcsv($line));

print_r(str_getcsv(线)美元);

Outputs:

输出:

Array
(
    [0] => 500,000
    [1] => 2
    [2] => 50
    [3] => 2
    [4] => 90000
)

Similar to fgetcsv() this functions parses a string as its input unlike fgetcsv() which takes a file as its input.

与fgetcsv()类似,此函数解析字符串作为输入,而fgetcsv()则将文件作为输入。

#2


1  

Try fgetcsv.

试:。

#1


2  

You can use the str_getcsv function

您可以使用str_getcsv函数

print_r(str_getcsv($line));

print_r(str_getcsv(线)美元);

Outputs:

输出:

Array
(
    [0] => 500,000
    [1] => 2
    [2] => 50
    [3] => 2
    [4] => 90000
)

Similar to fgetcsv() this functions parses a string as its input unlike fgetcsv() which takes a file as its input.

与fgetcsv()类似,此函数解析字符串作为输入,而fgetcsv()则将文件作为输入。

#2


1  

Try fgetcsv.

试:。