Love Fuel?    Donate

FuelPHP Forums

Ask your question about FuelPHP in the appropriate forum, or help others by answering their questions.
Format class having trouble with CSV files?
  • Attempting to import a CSV file from file upload. Here is a snippet of code: 

    $file_contents = file_get_contents($file['saved_to'].$file['saved_as']);
    $array = Format::forge($file_contents, 'csv')->to_array();

    In this example, $array is always empty. Looking into the Format class' _from_csv method, I see that the issue appears to stem from here: 

    $rows = preg_split('/(?<='.preg_quote(\Config::get('format.csv.import.enclosure', \Config::get('format.csv.enclosure', '"'))).')'.\Config::get('format.csv.regex_newline', '\n').'/', trim($string));

    The above returns one giant string and doesn't split up the file by rows. E.g., my CSV has two rows. the first row is Jane Doe, the second is for John Doe. Output of the above $rows using Debug::dump:

    (String): ""Jane","Doe","jane@doe.com",3434534,1,"asdfasdf",23432
    "John","Doe","john@doe.com",52939494,1,"dfdfdf",35353"
    (108 characters)


    This means that the following lines in _from_csv which grabs the headers (and slices off the first index of $rows) actually slices off all of the elements of the array. 

    I thought that perhaps my newline config settings were incorrect as they are set to FuelPHP's default settings. However, looking at my CSV file, all newlines appear to be using the newline character \n. I can provide an example CSV if that will help. 

    Edit:

    To further clarify, I have tried creating and saving a CSV from both LibreOffice and GoogleDocs. Both methods produce the same error. 
  • Fixed, https://github.com/fuel/core/commit/77e409e188804287ad8db7b3913be8f5f54b9b57

    Please create an issue on github for bugs please, it makes it easier to track them. Also, I'm the only dev that checks these forums, so if I'm away, nobody will pick them up...
  • HarroHarro
    Accepted Answer
    Looking at this again, there are two problems:

    The first is that your CSV export doesn't have a field header, and this is required for the Format class.

    The second is that the method used to split the lines in the string can't deal with a number as last element. You'll see that it will work if you have a string an the end.

    You'll have to fix the first one, I'll try to find a solution for the second one.
  • Thanks Harro! 

    I'll add the headers to the CSV and see if I can find some way for now to rework the order of the columns so that they don't have a number at the end. 
  • There's a new version of the Format class in 1.8/develop, which should be able to deal with numbers not enclosed in quotes...
  • Just copied it into the core and it works perfectly. Many thanks!
  • Cool, thanks for the feedback!

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion