Question

I have this PHP:

$handle = fopen($_FILES["csvfile"]["tmp_name"], "r");

while (($data = fgetcsv($handle, 5000, ",", '"')) !== FALSE) {
    echo "<pre>";
    print_r($data);
    echo "<pre>";
}

<form method="post">
<input type="file" name="csvfile">
<input type="submit>

The CSV is provided by an html <input type="file">. Right now it is printing out arrays that are only the first value and a comma or each row instead of printing out an array of eleven values of each row. I got it to do the right thing, but somehow messed up my code and can't figure out what I did.

Here is an example of the CSV:

"lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing","elit","sed ","diam","nonummy",
Was it helpful?

Solution

On the same code you posted i get a nice formatted result

file_put_contents( 'tmp.tmp',
'"lorem","ipsum","dolor","sit","amet","consectetuer","adipiscing","elit","sed ","diam","nonummy",
"1lorem","1ipsum","1dolor","1sit","amet","consectetuer","adipiscing","elit","sed ","diam","nonummy",
');

$handle = fopen("tmp.tmp", "r");

while (($data = fgetcsv($handle, 5000, ",", '"')) !== FALSE) {
    echo "<pre>";
    print_r($data);
    echo "<pre>";
}

I get:

Array ( [0] => lorem [1] => ipsum [2] => dolor [3] => sit [4] => amet [5] => consectetuer [6] => adipiscing [7] => elit [8] => sed [9] => diam [10] => nonummy [11] => )

You're probaly doing something wrong somewhere else, and not noticing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top