If you want to skip blank lines when reading a CSV file, you need *all * the flags:
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
(PHP 5 >= 5.1.0, PHP 7)
SplFileObject类为文件提供了一个面向对象接口.
$delimiter = ","
[, string $enclosure = "\""
[, string $escape = "\\"
]]] )$fields
[, string $delimiter = ","
[, string $enclosure = '"'
[, string $escape = "\"
]]] )$delimiter = ","
[, string $enclosure = "\""
[, string $escape = "\\"
]]] )$open_mode = "r"
[, bool $use_include_path = false
[, resource $context = NULL
]]] )SplFileObject::DROP_NEW_LINEDrop newlines at the end of a line.
SplFileObject::READ_AHEADRead on rewind/next.
SplFileObject::SKIP_EMPTYSkips empty lines in the file. This requires the READ_AHEAD flag be enabled, to work as expected.
SplFileObject::READ_CSVRead lines as CSV rows.
| 版本 | 说明 |
|---|---|
| 5.3.9 |
SplFileObject::SKIP_EMPTY value changed to 4.
Previously, value was 6.
|
If you want to skip blank lines when reading a CSV file, you need *all * the flags:
$file->setFlags(SplFileObject::READ_CSV | SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY | SplFileObject::DROP_NEW_LINE);
Note that this class has a private (and thus, not documented) property that holds the file pointer. Combine this with the fact that there is no method to close the file handle, and you get into situations where you are not able to delete the file with unlink(), etc., because an SplFileObject still has a handle open.
To get around this issue, delete the SplFileObject like this:
---------------------------------------------------------------------
<?php
print "Declaring file object\n";
$file = new SplFileObject('example.txt');
print "Trying to delete file...\n";
unlink('example.txt');
print "Closing file object\n";
$file = null;
print "Deleting file...\n";
unlink('example.txt');
print 'File deleted!';
?>
---------------------------------------------------------------------
which will output:
---------------------------------------------------------------------
Declaring file object
Trying to delete file...
Warning: unlink(example.txt): Permission denied in file.php on line 6
Closing file object
Deleting file...
File deleted!
---------------------------------------------------------------------