parsecsv / parsecsv-for-php

CSV data parser for PHP.
MIT License
681 stars 176 forks source link

Manually Force number of columns for unparse() #205

Open MDBenson opened 3 years ago

MDBenson commented 3 years ago

I have a CSV output requirement that is fighting parseCSV's unparse() method something fierce because the data is not a simple flat file, I am reporting a line then a 'subreport' table below that line and then flattening it all into a single CSV e.g.:

"Kit SKU","Name","Parts List","Price"    #Main CSV
00001,Widget 1,(See Below), 12.23
,Part,Description,Supplier,Qty,Cost    #Additonal Data
,PRT-001, Widget Component 1,ABC,2,0.99
,PRT-002,Widget Component 2,EEF,4,1.28
,,,,6,7.10    # Subreport totals

#Additional data is added into the main $csv->data from $subreport_csv->data.
#Line 1 mirrors the subreports headers into line [0] of the data.
#The empty first cell effectively indents the subreport table in the resulting spreadsheet

The problem I am having is the main titles are only 4 columns and parseCSV is assumingthe CSV is only 4 columns wide and truncating the additional data. When I try to use unparse() or output($file) it's screwing up the subreport data in all sorts of interesting ways, like skipping some of the columns. I have have to add 'phoney' $csv->titles[] elements in that add extra columns, but found these have to be unique and also have to contain text (I can't for example make them a blank space like " ", or just repeated "-" titles).

It would be very beneficial if I could just force parseCSV to respect the maximum width of columns in the data and override it's 'best guess' attempts which are extremely problematic.

Is this possible to dothis already? If not then could it be added?

gogowitsch commented 3 years ago

I am not sure if ParseCsv can handle this. I might research this further once I reserve time for this.

If you have solved it in the mean time: pull requests are welcome.

MDBenson commented 3 years ago

I mean, in essence all it needs is a method that allows:

$csv->columns = 10;

Or similar to lock the number of columns.

The rest is complex and I agree it's beyond ParseCsv's scope.

gogowitsch commented 2 months ago

Pull requests to improve this library are welcome. 😇