Skip to content

Instantly share code, notes, and snippets.

@77web
Last active August 29, 2015 14:02
Show Gist options
  • Save 77web/032f60e6ca378747898f to your computer and use it in GitHub Desktop.
Save 77web/032f60e6ca378747898f to your computer and use it in GitHub Desktop.
strange behavior of \SplTempFileObject and php://temp
test1 test2 test3
test4 test5 test6
<?php
echo "fopen\n";
$fp = fopen(__DIR__.'/test.csv', 'r');
fgetcsv($fp);
fgetcsv($fp);
var_dump(ftell($fp)); // int(36)
var_dump(feof($fp)); // bool(false)
fclose($fp);
echo "SplFileObject\n";
$fo = new \SplFileObject(__DIR__.'/test.csv', 'r');
$fo->setFlags(\SplFileObject::READ_CSV);
$fo->seek(1);
var_dump($fo->ftell()); // int(36)
var_dump($fo->eof()); // bool(false)
echo "SplTempFileObject\n";
$tmp = new \SplTempFileObject();
$tmp->fwrite(file_get_contents(__DIR__.'/test.csv'));
$tmp->rewind();
$tmp->setFlags(\SplFileObject::READ_CSV);
$tmp->seek(1);
var_dump($tmp->ftell()); // int(36)
var_dump($tmp->eof()); // bool(true)
echo "SplFileObject with php://temp\n";
$fo2 = new \SplFileObject('php://temp', 'r+');
$fo2->fwrite(file_get_contents(__DIR__.'/test.csv'));
$fo2->rewind();
$fo2->setFlags(\SplFileObject::READ_CSV);
$fo2->seek(1);
var_dump($fo2->ftell()); // int(36)
var_dump($fo2->eof()); // bool(true)
@77web
Copy link
Author

77web commented Jun 14, 2014

Only \SplTempFileObject returns true when I check whether eof or not.Why?
I suppose the pointer must be at the top of 2nd line, just before test4. Of course it does not reach EOF yet.

@77web
Copy link
Author

77web commented Jun 16, 2014

UPDATE: I found that \SplFileObject with php://temp is just the same as \SplTempFileObject.

@77web
Copy link
Author

77web commented Jun 16, 2014

UPDATE: even if \SplTempFileObject(or \SplFileObject with php://temp) returns true to eof(), I can get the last line by calling current().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment