fgetcsv — 从文件指针中读入一行并解析 CSV 字段
<?php
$row = 1;
$handle = fopen("test.csv","r");
while ($data = fgetcsv($handle, 1000, ",")) {
$num = count($data);
echo "<p> $num fields in line $row: <br>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br>\n";
}
}
fclose($handle);
?>
fputcsv — 将行格式化为 CSV 并写入文件指针
<?php
$list = array (
'aaa,bbb,ccc,dddd',
'123,456,789',
'"aaa","bbb"'
);
$fp = fopen('file.csv', 'w');
foreach ($list as $line) {
fputcsv($fp, split(',', $line));
}
fclose($fp);
?>
file — 把整个文件读入一个数组中
和 file_get_contents() 一样,只除了 file() 将文件作为一个数组返回。数组中的每个单元都是文件中相应的一行,包括换行符在内。如果失败 file() 返回 FALSE。
<?php
// 将一个文件读入数组。本例中通过 HTTP 从 URL 中取得 HTML 源文件。
$lines = file('http://www.example.com/');
// 在数组中循环,显示 HTML 的源文件并加上行号。
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
// 另一个例子将 web 页面读入字符串。参见 file_get_contents()。
$html = implode('', file ('http://www.example.com/'));
?>
file_put_contents — 将一个字符串写入文件
和依次调用 fopen(),fwrite() 以及 fclose() 功能一样。
<?php
$myFile = 'test.txt';
$myContent = 'I love PHP';
file_put_contents($myFile, utf8_encode($myContent));
?>
读取文件的一行
<?php
$file = fopen("test.txt","r");
while(! feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
?>
本文介绍PHP中处理文件的多种方法,包括使用fgetcsv和fputcsv进行CSV文件的读写,利用file函数将文件内容读入数组,通过file_put_contents简化文件写入过程,以及演示如何逐行读取文本文件。
357

被折叠的 条评论
为什么被折叠?



