What function or command can be used to specify which lines to read from a file and write to another file in PHP?
To specify which lines to read from a file and write to another file in PHP, you can use a combination of file handling functions like `fgets()` to read individual lines and `fwrite()` to write those lines to the new file. You can keep track of the line numbers you want to read/write and only process those lines accordingly.
$sourceFile = 'source.txt';
$destinationFile = 'destination.txt';
$linesToCopy = [1, 3, 5]; // Specify the line numbers to copy
$sourceHandle = fopen($sourceFile, 'r');
$destinationHandle = fopen($destinationFile, 'w');
$lineNumber = 1;
while (!feof($sourceHandle)) {
$line = fgets($sourceHandle);
if (in_array($lineNumber, $linesToCopy)) {
fwrite($destinationHandle, $line);
}
$lineNumber++;
}
fclose($sourceHandle);
fclose($destinationHandle);
Related Questions
- What are the potential benefits of using ModRewrite for handling 404 errors in PHP?
- How can PHP developers handle arrays with varying depths when deleting specific elements?
- What are some alternative methods to troubleshoot PHP code when traditional methods like Google searches do not yield results?