Delete last line and check data in text file

2019-08-31 18:58发布

问题:

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"; 
} 

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.

check for duplicate value in text file/array with 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
?>

Thanks for any help from a PHP newbie.

回答1:

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


标签: php fwrite