2

whats wrong with this, when i echo out a row from the csv file and concat anything to the end of the row, it doesnt show up, instead all the rows are echo'ed and the concated string only shows up once at the very end, is this some kind of buffering thing that wont let me concat strings with stuff from my csv file, its running on my local wamp server, and i have tryed different line delimiter in my expload function, im sure the file only uses \n at the end of a line

im trying to parse a csv file row by row so i can check the content of it before i use it to construct an sql statement and insert it into my database.

$file = fopen($filename, "r")  
$filesize = filesize($filename);
$filecontent = fread($file, $filesize);
fclose($file); 

$rows = explode("\n", trim($filecontent)); 
foreach ($rows as $row) 
{
    echo $row . '<br />';
} 
1
  • sorry guys my bad, i dont have control of the script that generates the csv file and the guy who does told me to use the wrong line delimeter, my problem is solved now. Commented Dec 28, 2010 at 10:25

2 Answers 2

2

You are splitting the string by the string \n. Unless the actual string "\n" appears anywhere in the file, this will probably do nothing. You probably meant "\n" (double quotes), which makes this an actual line break.

Your overall process is terribly inefficient though. You should use fgetcsv and process the file line by line, instead of reading it into memory all at once.

$handle = fopen('test.csv', 'r');
while (($row = fgetcsv($handle)) !== false) {
    foreach ($row as $field) {
        echo $field . '<br />';
    }
}
fclose($handle);
Sign up to request clarification or add additional context in comments.

1 Comment

the double quotes thig was just a copy+past error so it wasnt the problem, but i tryed your code and still got the same behavior i described, the br tag appears after every field instead of after every line, if i echo something before or after the for loop it will only appear once
0

Use fgetcsv() function to convert a CSV file to an array:

$csvFile = "test.csv";
$csvSeparator = ",";
$csvFileLength = filesize($csvFile);

$handle = fopen($csvFile, "r");
    $csvData = fgetcsv($handle, $csvFileLength, $csvSeparator);
fclose($handle);

Dump the data to show the structure:

var_dump($csvData);

Now you can convert the data to use in database.

1 Comment

i have played with fgetcsv before, i tryed every example at php.net but still have the same problem, fgetcsv just returns every field in the csv file in one single array, i dont think it is reading the line delimiter properly, i think its set to \r\n by default and cant be changed.

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.