Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Practically Split Values from CSV File into MySQL Database

Tags:

regex

php

mysql

csv

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

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

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

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

"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?

like image 480
Ryan Avatar asked Jul 21 '26 18:07

Ryan


2 Answers

You can use the str_getcsv function

print_r(str_getcsv($line));

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.

like image 198
Russell Dias Avatar answered Jul 23 '26 08:07

Russell Dias


Try fgetcsv.

like image 28
Emil Vikström Avatar answered Jul 23 '26 07:07

Emil Vikström