[英]PHP Edit first line of a text file
我正在尝试通过PHP编辑文本文件的第一行。 我已经分解了脚本并通过1对功能进行了测试。我删除第1行的工作正常。 但是,然后我尝试在开头插入一行,然后将文件擦除为零,然后将其写入。
我的代码:
<?php
$filename = $_GET['jobname'];
$sunits = $_GET['s'];
$wunits = $_GET['w'];
$funits = $_GET['f'];
$vunits = $_GET['v'];
$tunits = $_GET['t'];
$data = "S: $sunits - W: $wunits - F: $funits - V: $vunits - T: $tunits";
$f = "$filename.txt";
// read into array
$arr = file($f);
// remove second line
unset($arr[0]);
// reindex array
$arr = array_values($arr);
// write back to file
file_put_contents($f,implode($arr));
$handle = fopen("$filename.txt", 'r+') or die('Cannot open file: '.$filename);
fwrite($handle, $data . "\n");
fclose($handle);
?>
谁能看到我在做什么错?
谢谢
我只会使用file_get_contents() [file() in your case] + file_put_contents()
。
之后不需要使用fopen() file_put_contents()
实际上在调用file_put_contents()
时会调用它。
<?php
$filename = $_GET['jobname'];
$sunits = $_GET['s'];
$wunits = $_GET['w'];
$funits = $_GET['f'];
$vunits = $_GET['v'];
$tunits = $_GET['t'];
$data = "S: $sunits - W: $wunits - F: $funits - V: $vunits - T: $tunits";
$f = "$filename.txt";
// read into array
$arr = file($f);
// edit first line
$arr[0] = $data;
// write back to file
file_put_contents($f, implode($arr));
?>
您可能需要使用implode(PHP_EOL,$arr)
因此数组的每个元素都位于其自己的行上
您不能在文本文件的开头添加一行,而只能在结尾添加一行。 您要做的是将新行添加到数组的开头,然后将整个数组写回:
// Read the file
$fileContents = file('myfile.txt');
// Remove first line
array_shift($fileContents);
// Add the new line to the beginning
array_unshift($fileContents, $data);
// Write the file back
$newContent = implode("\n", $fileContents);
$fp = fopen('myfile.txt', "w+"); // w+ means create new or replace the old file-content
fputs($fp, $newContent);
fclose($fp);
您的问题来自使用file_put_contents ,如果文件不存在则创建一个文件,或者清除文件然后写入内容。 在您的情况下,您需要在附加模式下使用fopen ,使用fwrite写入数据,然后使用fclose关闭文件。 确切的代码中可能会再走一两个步骤,但这是将数据追加到已包含内容的文件中的一般思想。
最后我要做的不是unset $arry[0]
而是设置$arr[0] = $data . "\\n"
$arr[0] = $data . "\\n"
,然后放回该文件,它可以正常工作。 有人看到这样做有任何问题吗?
我整夜都在研究。 这是我能找到的最佳解决方案。 快速,资源少。 当前,此脚本将回显内容。 但是您始终可以保存到文件。 以为我会分享。
$fh = fopen($local_file, 'rb');
echo "add\tfirst\tline\n"; // add your new first line.
fgets($fh); // moves the file pointer to the next line.
echo stream_get_contents($fh); // flushes the remaining file.
fclose($fh);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.