SplFileObject always returns an extra "last" line -- why? [message #186318] |
Tue, 24 June 2014 14:09 |
kurtk(at)pobox(dot)com
Messages: 10 Registered: May 2012
Karma: 0
|
Junior Member |
|
|
Why does SplFileObject always seems to return an extraneous, final empty string as an extra last line of file.
If I have a file with only one line of text and run this code
try {
$file = new SplFileObject("./one.txt");
} catch (Exception $e) {
echo $e->getMessage() . "\n";
}
foreach($file as $line_no => $contents) {
echo "line number " . $line_no . " is: " . $contents;
}
I get two lines of output:
line number 0 is: one
line number 1 is:
The file one has one line of text, the word "one". I'm running this on Linux Mint 17 with PHP 5.5.9.
Thanks
|
|
|
Re: SplFileObject always returns an extra "last" line -- why? [message #186319 is a reply to message #186318] |
Tue, 24 June 2014 14:22 |
Christoph Michael Bec
Messages: 207 Registered: June 2013
Karma: 0
|
Senior Member |
|
|
kurtk(at)pobox(dot)com wrote:
> Why does SplFileObject always seems to return an extraneous, final
> empty string as an extra last line of file.
>
> If I have a file with only one line of text and run this code
>
> try {
> $file = new SplFileObject("./one.txt");
>
> } catch (Exception $e) {
> echo $e->getMessage() . "\n";
> }
>
> foreach($file as $line_no => $contents) {
>
> echo "line number " . $line_no . " is: " . $contents;
>
> }
>
> I get two lines of output:
> line number 0 is: one
> line number 1 is:
>
> The file one has one line of text, the word "one". I'm running this
> on Linux Mint 17 with PHP 5.5.9.
Actually the file has two lines, because you're having a line break (NL,
CR or CRLF) after the word "one", I assume. Either remove this line
break, or set appropriate flags for $file:
$file->setFlags(
SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY
);
See <http://www.php.net/manual/en/splfileobject.setflags.php>.
--
Christoph M. Becker
|
|
|
Re: SplFileObject always returns an extra "last" line -- why? [message #186325 is a reply to message #186319] |
Wed, 25 June 2014 01:14 |
kurtk(at)pobox(dot)com
Messages: 10 Registered: May 2012
Karma: 0
|
Junior Member |
|
|
> Actually the file has two lines, because you're having a line break (NL,
> CR or CRLF) after the word "one", I assume. Either remove this line
> break, or set appropriate flags for $file:
>
> $file->setFlags(
> SplFileObject::READ_AHEAD | SplFileObject::SKIP_EMPTY
> );
Thanks Christoph! That worked. Now I know how to set the flags to get the behaviour I need.
|
|
|