0

I created a CSV parser that works fine for some CSV files I've found online, but one that I converted from XLS to CSV via Microsoft Excel 2011 does not work. The ones that work are formatted as such:

"Sort Order","Common Name","Formal Name","Type","Sub Type","Sovereignty","Capital","ISO 4217 Currency Code","ISO 4217 Currency Name","ITU-T Telephone Code","ISO 3166-1 2 Letter Code","ISO 3166-1 3 Letter Code","ISO 3166-1 Number","IANA Country Code TLD" "1","Afghanistan","Islamic State of Afghanistan","Independent State",,,"Kabul","AFN","Afghani","+93","AF","AFG","004",".af".........................etc...

The one that doesn't work is formatted like this:

Order Id,Date Ordered,Date Returned,Product Id,Description,Order Reason Code,Return Qty,Order Return Comment,Ship To Name,Ship To Address1,Ship To Address2,Ship To Address3,Ship To City,Ship To State,Ship To Zipcode,Ship To Country,Disposition,Ship To Email,ShipVia 5555555,2013-07-05 13:58:36.000,2013-08-16 00:00:00.000,5555-55,0555 - Some Test Thing,Refund,2,,jeric beatty,123 fake st,,,burke,NJ,55055,US,Discard,test@test.com,Super Fast Shipping

Is there anyway to get excel to export in the format as the first one? I would like to avoid doing this manually as the file is huge and I would have to manually edit lots of parts of it where I couldn't do a "replace all". Another issue could be that there are double and sometimes triple commas in some places. Though this does appear in both files.

Here is the parser:

    function ingest_csv() {

  $file_url = 'http://www.path.to/csv/file.csv';
  $record_num = 0;
  $records = array();
  $header = array();
  if (($handle = fopen($file_url, "r")) !== FALSE) {
    $records['id'] = '';
    while (($data = fgetcsv($handle)) !== FALSE) {
      $records['id'][$record_num] = '';
      $cell_num = 0;
      foreach ($data as $cell) {
        if($record_num == 0) {
          $header = $data;
        } else {
          $current_key = $header[$cell_num];
          $records['id'][$record_num][$current_key] = $cell;
        }
        $cell_num++;
      }
      $record_num++;

    }

    fclose($handle);
  }
  else {
    echo 'could not open file.';
  }
  return array($record_num, $records);
}

function batch_csv() {
  list($num_rows, $rows) = ingest_csv
  print_r($num_rows);
  print_r($rows);
}
4

1 回答 1

1

正如评论中提到的,尽管您可能正在尝试在这里重新发明轮子,尽管我个人已经提出了一些问题,我不想对为什么我被迫使用非常规方法进行冗长的解释,所以这应该是其中之一这里有一个答案。

在 OpenOffice Calculator(例如)中,当您保存为 CSV 时,您会获得许多其他选项,包括决定对所有字段进行双引号。

不幸的是,Excel 没有给你选择,但微软确实提供了一个使用宏的解决方法 - http://support.microsoft.com/kb/291296/en-us

于 2013-09-23T22:09:01.680 回答