3

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Note that str_getcsv only works in PHP 5.3 and above. For earlier versions, "save" the string to the php://memory special file and use fgetcsv to parse it. Not that str_getcsv is really relevant to this question since the OP specifically have a file, so reading it one line at a time probably makes sense.
@Emil Yeah, I was just showing him an example using the $line variable he already had. At the bottom I stated what he should do for a csv file.
1

Try fgetcsv.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.