我有以下代码将数据写入文本文件。
$somecontent = "data|data1|data2|data3";
$filename = 'test.txt';
// Let's make sure the file exists and is writable first.
IF (IS_WRITABLE($filename)) {
// In our example we're opening $filename in append mode.
// The file pointer is at the bottom of the file hence
// that's where $somecontent will go when we fwrite() it.
IF (!$handle = FOPEN($filename, 'a')) {
PRINT "Cannot open file ($filename)";
EXIT;
}
// Write $somecontent to our opened file.
IF (!FWRITE($handle, $somecontent)) {
PRINT "Cannot write to file ($filename)";
EXIT;
}
PRINT "Success, wrote ($somecontent) to file ($filename)";
FCLOSE($handle);
} ELSE {
PRINT "The file $filename is not writable";
}
现在我希望这个文本文件只包含10行数据,当添加新行数据时,其他行是唯一的,然后删除最后一行数据并添加新的数据行。
从研究中我发现了以下代码,但完全不知道如何在上面的代码中实现它。
check for duplicate value in text file/array with php
以及实现以下代码的最简单方法是什么?
<?
$inp = file('yourfile.name');
$out = fopen('yourfile.name','w');
for ($I=0;$i<count($inp)-1);$i++)
fwrite($out,$inp[$I]);
fclose($out)l
?>
感谢PHP新手提供的任何帮助。
答案 0 :(得分:0)
$file = fopen($filename, "r");
$names = array();
// Put the name part of each line in an array
while (!feof($file)) {
$line_data = explode("|", $fgets($file));
$names[] = $line_data[0]
}
$data_to_add = "name|image|price|link"
$data_name = "name" // I'm assuming you have this in a variable somewhere
// If the new data does not exist in the array
if(!in_array($data_name, $names)) {
unset($lines[9]); // delete the 10th line
array_unshift($lines, $data_to_add); // Put new data at the front of the array
// Write the new array to the file
file_put_contents($filename, implode("\n", $lines));
}