超越PHP PHP动态 | 经典文章 | CLASS | 相关下载 | 常见问题 | FORUM | WIKI | 在线手册
Site search:    
<fgetcfgets>
Last updated: Fri, 22 Jun 2007

fgetcsv

(PHP 3>= 3.0.8, PHP 4 , PHP 5)

fgetcsv -- 从文件指针中读入一行并解析 CSV 字段

说明

array fgetcsv ( int handle, int length [, string delimiter [, string enclosure]])

fgets() 类似,只除了 fgetcsv() 解析读入的行并找出 CSV 格式的字段然后返回一个包含这些字段的数组。可选的第三个参数 delimiter 的默认值是逗号。可选参数 enclosure 的默认值是双引号。delimiterenclosure 都被限制为一个字符。如果多于一个字符,则只使用第一个字符。

注: enclosure 参数是 PHP 4.3.0 新加的。

handle 必须是通过 fopen()popen() 或者 fsockopen() 成功打开的有效文件指针。

length 必须大于 CVS 文件中长度最大的行(以便于处理行结束字符)。

fgetcsv() 出错时返回 FALSE,包括碰到文件结束时。

注: CSV 文件中的空行将被返回为一个包含有单个 null 字段的数组,不会被当成错误。

例子 1. 读取并显示 CSV 文件的整个内容

<?php
$row
= 1;
$handle = fopen ("test.csv","r");
while (
$data = fgetcsv ($handle, 1000, ",")) {
  
$num = count ($data);
   print
"<p> $num fields in line $row: <br>\n";
  
$row++;
   for (
$c=0; $c < $num; $c++) {
       print
$data[$c] . "<br>\n";
   }
}
fclose ($handle);
?>




add a note add a note User Contributed Notes
fgetcsv
blair at squiz . net
15-Aug-2001 10:19
Here is a function that takes an array and adds a CSV line to the passed file pointer.

<?php
function fputcsv ($fp, $array, $deliminator=",") {

 $line = "";
foreach($array as $val) {
   # remove any windows new lines,
# as they interfere with the parsing at the other end
   $val = str_replace("\r\n", "\n", $val);

   # if a deliminator char, a double quote char or a newline
   # are in the field, add quotes
   if(ereg("[$deliminator\"\n\r]", $val)) {
     $val = '"'.str_replace('"', '""', $val).'"';
   }#end if

   $line .= $val.$deliminator;

 }#end foreach

 # strip the last deliminator
 $line = substr($line, 0, (strlen($deliminator) * -1));
 # add the newline
 $line .= "\n";

 # we don't care if the file pointer is invalid,
 # let fputs take care of it
 return fputs($fp, $line);

}#end fputcsv()
?>

<fgetcfgets>
 Last updated: Fri, 22 Jun 2007
view source | feedback | send page | sitemap | aboutus   
Copyright ® 2002-2003 PHPE.NET. All rights reserved
Last updated:2002-11-22