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
= "\\"
]]] ) : array$fields
[, string $delimiter
= ","
[, string $enclosure
= '"'
[, string $escape
= "\\"
]]] ) : int$delimiter
= ","
[, string $enclosure
= "\""
[, string $escape
= "\\"
]]] ) : void$open_mode
= "r"
[, bool $use_include_path
= FALSE
[, resource $context
= NULL
]]] ) : SplFileObjectSplFileObject::DROP_NEW_LINE
Drop newlines at the end of a line.
SplFileObject::READ_AHEAD
Read on rewind/next.
SplFileObject::SKIP_EMPTY
Skips empty lines in the file. This requires the READ_AHEAD
flag be enabled, to work as expected.
SplFileObject::READ_CSV
Read 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!
---------------------------------------------------------------------