解决php fgetcsv 读取csv文件数据不完整问题
来源:程序员人生 发布时间:2014-04-19 14:39:06 阅读次数:4864次
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) {
-
-
- # 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);
- }
-
这个代码没有任何问题,然后我放到了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 .= (emptyempty ($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 emptyempty ($_line) ? false : $_csv_data;
- }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠