Professional Documents
Culture Documents
Một số hàm thao tác với files trong PHP
Một số hàm thao tác với files trong PHP
PHP Code:
$handle = @fopen("C:\\testlog.php", "r");
$allowable_tags = "<a>";
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss ($handle , 4096, $allowable_tags);
echo $buffer . "<br/>";
}
fclose($handle);
}
6.string file_get_contents ( string $filename [, int $flags [, resource $context [, int $offset [,
int $maxlen]]]] )
a.Function đọc nội dung file và trả về một chuỗi, hàm bắt đầu đọc từ giá trị offset đến $maxlen đã được
chỉ định, giá trị này tính theo bytes. Nếu thất bại thì hàm trả về FALSE
b.$flags chỉ có trong PHP6
7.fread ( resource $handle , int $length )
a.Đọc nội dung file giới hạn bởi $length(bytes)
b.Example:
PHP Code:
$source = "C:\\testlog.php";
$handle = fopen($source, "r");
$contents = fread($handle, filesize($source));
var_dump($contents); //ouput: string(158) "09:34:28 VirtualDisk
-....xxxxxxxx"
8.int file_put_contents ( string $filename, mixed $data [, int $flags [, resource $context]] )
a.Cho phép ghi nội dung vào file, nếu file ko tồn tại thì sẽ tạo file mới
b.$data ở đây có thể là một string, array hoặc stream resource. Nếu data là một array thì function này sẽ
tự động convert array thành string và ghi vào file. Việc convert này tương đương với việc ta dùng hàm
implode(“”, $array)
c.$flags ở đây nhận một số giá trị:
·FILE_APPEND: ghi tiếp tục vào file, ko ghi đè
·LOCK_EX: lock file trước khi ghi nội dung
PHP Code:
$source = "C:\\testlog.php";
$data = "This is a string";
$data2 = array('element 1', 'element 2','element 3');
$res = file_put_contents($source, $data2); //Content of file: element 1element
2element 3
$res1 = file_put_contents($source, $data); //Content of file: This is a string
9.array fgetcsv ( resource $handle [, int $length [, string $delimiter [, string $enclosure [,
string $escape]]]] )
a.Đọc nội dung file CSV theo từng dòng
10.int fputcsv ( resource $handle, array $fields [, string $delimiter [, string $enclosure]] )
a.Ghi nội dung ra file CSV
PHP Code:
$csvfile = "C:\\xxx.csv";
$csvfile2 = "C:\\xxx1.csv";
$f = fopen($csvfile, "r");
while ($r = fgetcsv($f)) {
$array[] = $r;
}
print "<pre>";
print_r($array);
$f2 = fopen($csvfile2, "w+");
foreach ($array as $v) {
fputcsv($f2,$v);
}
fclose($f);
fclose($f2);
Edit/Delete Message