[英]Write to file using SplFileObject()
我正在嘗試使用SplFileObject()逐行編輯文件。 我可以選擇要編輯的文件行。 但是,如何將$ string寫入該行呢?
以下是獲取該行的代碼:
<?php
$file = new SplFileObject('myfile.txt');
$file->seek(9999); // Seek to line no. 10,000
echo $file->current(); // Print contents of that line
?>
如何在該行上插入字符串?
注意,我不想覆蓋該文件,我只想在給定的行中插入$ string。
這可能不是最佳解決方案,因為它將讀取整個文件並將其存儲在字符串中。 但由於沒有其他答案,您可以將其用作最后一個資源。
$ouput = '';
$file = new SplFileObject("your_file.xxx", 'r');
while (!$file->eof()) {
$line = $file->fgets();
if($line == 'your_condition'){
$line = 'replace this line';
}
$output .= $line;
}
$file = null;
$file = new SplFileObject("your_file.xxx", 'w+');
$file->fwrite($output);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.