Asked  7 Months ago    Answers:  5   Viewed   40 times

The closest I've seen in the PHP docs, is to fread() a given length, but that doesnt specify which line to start from. Any other suggestions?

 Answers

92

You not going to be able to read starting from line X because lines can be of arbitrary length. So you will have to read from the start counting the number of lines read to get to line X. For example:

<?php
$f = fopen('sample.txt', 'r');
$lineNo = 0;
$startLine = 3;
$endLine = 6;
while ($line = fgets($f)) {
    $lineNo++;
    if ($lineNo >= $startLine) {
        echo $line;
    }
    if ($lineNo == $endLine) {
        break;
    }
}
fclose($f);
Wednesday, March 31, 2021
 
AlterPHP
answered 7 Months ago
60

You should first test the existence of a file by file_exists().

try
{
  $fileName = 'uploads/Team/img/'.$team_id.'.png';

  if ( !file_exists($fileName) ) {
    throw new Exception('File not found.');
  }

  $fp = fopen($fileName, "rb");
  if ( !$fp ) {
    throw new Exception('File open failed.');
  }  
  $str = stream_get_contents($fp);
  fclose($fp);

  // send success JSON

} catch ( Exception $e ) {
  // send error message if you can
} 

or simple solution without exceptions:

$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ) {

  $str = stream_get_contents($fp);
  fclose($fp);

  // send success JSON    
}
else
{
  // send error message if you can  
}
Wednesday, March 31, 2021
 
Crontab
answered 7 Months ago
97

This

foreach($matches[1] as $content)
     echo $content."rn";

only iterates over the array and makes $content the last element (you have no {} so it is a one liner).

Simple demo of your issue, https://eval.in/806352.

You could use use implode though.

fwrite($file,implode("nr", $matches[1]));

You also could simplify this by using file_put_contents. Per the manual:

This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.

So you could just do:

$re = '/<li><a href="(.*?)"/';
$str = '
<li><a href="http://www.example.org/1.html"</a></li>
                        <li><a href="http://www.example.org/2.html"</a></li>
                        <li><a href="http://www.example.org/3.html"</a></li> ';

preg_match_all($re, $str, $matches);
echo '<div id="pin" style="float:center"><textarea class="text" cols="110" rows="50">';
file_put_contents("1.txt", implode("nr", $matches[1]));
Wednesday, March 31, 2021
 
SubniC
answered 7 Months ago
39

The conceptual problem here is that files are just strings of characters, some of those characters denote ends of lines. Because of that, it is impossible to know where lines begin and end without reading the file first.

If a file is to be read constantly, you scan the file first and record the offsets for the lines into some kind of index and use fseek() and fread() to read exactly the lines you want.

As you mentioned, databases can do a similar job for you so, instead of creating, essentially, your own database, you could read the file line–by–line and insert those lines in database with some field storing the line number and then get the lines you want with a query.

Wednesday, March 31, 2021
 
FyodorX
answered 7 Months ago
50
myFile.renameTo(new File("/the/new/place/newName.file"));

File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).

Renames the file denoted by this abstract pathname.

Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile

Wednesday, June 2, 2021
 
leebriggs
answered 5 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :