删除最后一行并检查文本文件中的数据 [英] Delete last line and check data in text file

查看:100
本文介绍了删除最后一行并检查文本文件中的数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码将数据写入文本文件.

I have the following code to write data to a text file.

$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行数据,并且当添加新行的数据(对于其他行是唯一的)时,删除最后一行数据,并添加新行数据.

Now I want this text file to only every have 10 lines of data and when a new line of data is added which is unique to the other lines then the last line of data is deleted and a new line of data is added.

从研究中我发现以下代码,但是完全不知道如何在上述代码上实现它.

From research I have found the following code however total no idea how to implement it on the above code.

检查文本文件/数组中的重复值用php

以及实现以下代码的最简单方法是什么?

and also what is the easiest way to implement the following code?

<?
$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新手的任何帮助.

Thanks for any help from a PHP newbie.

推荐答案

$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));
}

这篇关于删除最后一行并检查文本文件中的数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆