Read the csv file and create another csv file using php

I have a .csv file, and when I open it through notepad, it looks like this:

 ID501501503502 

And when I print it in the browser via php, it looks like

 ID 501 501 503 502 

My code is:

 $handle = fopen("MonC1.csv", "r"); $data = fgetcsv($handle, 0); $fh = fopen('php://output', 'w'); if (! empty($data)) { foreach ($data as $item) { echo $item."<br>"; //fputcsv($fh, array($item)); } } 

So basically the br tag inside the for loop does not work. This is my first problem.

And the second problem, even if I use fputcsv(now it is turned off) , it does not create the actual csv file.

Now I have a question, why doesn’t it have a place in the notebook, and when I type in the browser, does it get a space?

I have only one column and nothing else.

Any help is greatly appreciated. Thanks in advance.

+5
source share
1 answer

As mentioned in my comment, it looks like your source file is saved with the end of the UNIX line, and then you use fgetcsv on Windows, so the whole file is read as a single line. Probably one <br> at the end of the whole conclusion.

So, before processing your file, you need to pre-process it in order to convert line endings.

On Linux, unix2dos does what you want. Or you can simply replace \n with \r\n in your file.

Another problem is that fgetcsv does not turn the entire file into an array. Instead, it reads one line from the file descriptor and converts it to an array. You will need to read the lines inside the loop:

 while (($data = fgetcsv($handle)) !== FALSE) { // $data contains one line of the CSV, in array form // now you can fputcsv the single line } 
+1
source

Source: https://habr.com/ru/post/1209155/


All Articles