csv文件是在php中有fgetcsv函數來讀取,但在linux是的php5.2.8版本中會發現fgetcsv讀出來的csv文件數據不完整,下面我們來看問題解決辦法。
在windows其它版本中
代碼如下 復制代碼# Open the File.
if (($handle = fopen("test.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$nn = 0;
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
//print_r($data);
# Count the total keys in the row.
$c = count($data);
# Populate the multidimensional array.
for ($x=0;$x<$c;$x++)
{
$csvarray[$nn][$x] = $data[$x];
}
$nn++;
}
# Close the File.
fclose($handle);
}
//print_r($csvarray);
這個代碼沒有任何問題,然後我放到了linux中發現有為空的字段了。
問題解析出來的數據不完整,有為空的字段
網上查了下說是在php5.2.8 中存在bug
解決辦法是使用自定義函數
function __fgetcsv(& $handle, $length = null, $d = ',', $e = '"') {
$d = preg_quote($d);
$e = preg_quote($e);
$_line = "";
$eof=false;
while ($eof != true) {
$_line .= (empty ($length) ? fgets($handle) : fgets($handle, $length));
$itemcnt = preg_match_all('/' . $e . '/', $_line, $dummy);
if ($itemcnt % 2 == 0)
$eof = true;
}
$_csv_line = preg_replace('/(?: |[ ])?$/', $d, trim($_line));
$_csv_pattern = '/(' . $e . '[^' . $e . ']*(?:' . $e . $e . '[^' . $e . ']*)*' . $e . '|[^' . $d . ']*)' . $d . '/';
preg_match_all($_csv_pattern, $_csv_line, $_csv_matches);
$_csv_data = $_csv_matches[1];
for ($_csv_i = 0; $_csv_i < count($_csv_data); $_csv_i++) {
$_csv_data[$_csv_i] = preg_replace('/^' . $e . '(.*)' . $e . '$/s', '$1' , $_csv_data[$_csv_i]);
$_csv_data[$_csv_i] = str_replace($e . $e, $e, $_csv_data[$_csv_i]);
}
return empty ($_line) ? false : $_csv_data;
}