PyRoss
PyRoss

Reputation: 129

PHP SplFileObject error

Wanted to seperate each line in the text file, reverse the order and echo it. Got Method SplFileObject::__toString() must return a string value error.

Here's the code:

for ($x=$lines; $x>0; $x--) {
    $file = new SplFileObject("post.txt");
    $file -> seek($x);
    echo $file;
}

Upvotes: 2

Views: 633

Answers (2)

Josh from Qaribou
Josh from Qaribou

Reputation: 6908

You're simply seeking to a line longer than the file you've input.

This is an issue for you with these files, because you won't know how many lines are in a file until you've iterated to the end. A text file's number of lines isn't something stored in the file's metadata - it's not like the filesize. SplFileObject is intended to use its iterator, which can only seek() (go forward from the start to a specific line -- fairly slow if you're reversing lines this way), next(), or rewind() (go back to the start). It's an excellent class to use if you want to read through a file, but not great for going backwards the way you've indicated.

To get lines backwards from the end, you'll want to use an array where each item is a line in your file. That's the intended use of the old builtin file ( http://php.net/manual/en/function.file.php ).

If your heart is set on an SplFileObject, because you want to use it elsewhere in your code, you can build an array in reverse like so:

$lines = [];
foreach (new SplFileObject('test.txt') as $line) {
    array_unshift($lines, $line);
}

echo implode('', $lines);

Upvotes: 1

hek2mgl
hek2mgl

Reputation: 158080

I would use good old file() together with array_reverse():

foreach(array_reverse(file('file.txt')) as $line) {
    echo $line;
}

Upvotes: 1

Related Questions