Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<h2>EDITED 01</h2> <p>If what you need is the number of lines inside the file:</p> <pre><code>&lt;?php $path = tempnam(sys_get_temp_dir(), '').'.txt'; $fileInfo = new SplFileInfo($path); $fileObject = $fileInfo-&gt;openFile('a+'); $fileObject-&gt;fwrite("Foo".PHP_EOL); $fileObject-&gt;fwrite("Bar".PHP_EOL); echo count(file($path)); // outputs 2 ?&gt; </code></pre> <hr> <p><br/></p> <h2>EDITED 02</h2> <p>This is your code above, but without entering into infinite loops due to the file pointer:</p> <pre><code>&lt;?php $path = tempnam(sys_get_temp_dir(), '').'.txt'; $fileInfo = new SplFileInfo($path); $fileObject = $fileInfo-&gt;openFile('a+'); $fileObject-&gt;fwrite("Foo".PHP_EOL); $fileObject-&gt;fwrite("Bar"); foreach($fileObject as $line_num =&gt; $line) { echo 'Line: '.$line_num.' "'.$line.'"'."&lt;br/&gt;"; } echo 'Total Lines:' . $fileObject-&gt;key(); ?&gt; </code></pre> <p><strong>Outputs</strong></p> <blockquote> <p>Line: 0 "Foo "</p> <p>Line: 1 "Bar"</p> <p>Total Lines:2</p> </blockquote> <hr> <p><br/></p> <h2>ORIGINAL ANSWER</h2> <p>The logic applied was a bit off. I simplified the code:</p> <pre><code>&lt;?php // set path to tmp with random file name echo $path = tempnam(sys_get_temp_dir(), '').'.txt'; echo "&lt;br/&gt;"; // new object $fileInfo = new \SplFileInfo($path); // open to write $fileObject = $fileInfo-&gt;openFile('a'); // write two lines $fileObject-&gt;fwrite("Foo".PHP_EOL); $fileObject-&gt;fwrite("Bar".PHP_EOL); // open to read $fileObject2 = $fileInfo-&gt;openFile('r'); // output contents echo "File Exists: " .file_exists($path); echo "&lt;br/&gt;"; echo "File Contents: " . file_get_contents($path); echo "&lt;br/&gt;"; // foreach line get line number and line contents foreach($fileObject2 as $line_num =&gt; $line) { echo 'Line: '.$line_num; echo ' With: "'.$line.'" is the end? '.($fileObject2-&gt;eof()?'yes':'no')."&lt;br&gt;"; } ?&gt; </code></pre> <p><strong>Outputs:</strong></p> <blockquote> <p>/tmp/EAdklY.txt</p> <p>File Exists: 1</p> <p>File Contents: Foo Bar </p> <p>Line: 0 With: "Foo " is the end? no</p> <p>Line: 1 With: "Bar " is the end? no</p> <p>Line: 2 With: "" is the end? yes</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload