解决php fgetcsv 读取csv文件数据不完整问题

csv文件是在php中有fgetcsv函数来读取,但在linux是的php5.2.8版本中会发现fgetcsv读出来的csv文件数据不完整,在windows其它版本中,代码如下:

  1. # Open the File.
  2. if (($handle = fopen("test.csv", "r")) !== FALSE) {
  3. # Set the parent multidimensional array key to 0.
  4. $nn = 0;
  5. while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
  6. //print_r($data);
  7. # Count the total keys in the row.
  8. $c = count($data);
  9. # Populate the multidimensional array.
  10. for ($x=0;$x<$c;$x++)
  11. {
  12. $csvarray[$nn][$x] = $data[$x];
  13. }
  14. $nn++;
  15. }
  16. # Close the File.
  17. fclose($handle);
  18. }
  19. //print_r($csvarray);

这个代码没有任何问题,然后我放到了linux中发现有为空的字段了,问题解析出来的数据不完整,有为空的字段,网上查了下说是在php5.2.8 中存在bug,解决办法是使用自定义函数,代码如下:

  1. function __fgetcsv(& $handle, $length = null, $d = ',', $e = '"') {
  2. $d = preg_quote($d);
  3. $e = preg_quote($e);
  4. $_line = "";
  5. $eof=false;
  6. while ($eof != true) {
  7. $_line .= (emptyempty ($length) ? fgets($handle) : fgets($handle, $length));
  8. $itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
  9. if ($itemcnt % 2 == 0)
  10. $eof = true;
  11. }
  12. $_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
  13. $_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
  14. preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
  15. $_csv_data = $_csv_matches[1];
  16. for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
  17. $_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1' , $_csv_data[$_csv_i]);
  18. $_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
  19. }
  20. return emptyempty ($_line) ? false : $_csv_data;
  21. }