0

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.

Community
  • 1
  • 1

1 Answers1

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));
}
Cameron Ball
  • 4,048
  • 6
  • 25
  • 34
  • My data on each line is separated by a "|", is it possible to check the piece of data instead of checking all of the line to make sure the data is unique? – user3134976 Dec 26 '13 at 11:50
  • Can you clarify a bit more? I don't quite understand. Are you saying that you only want ONE line in the text file with a maximum of ten pieces of data? – Cameron Ball Dec 26 '13 at 14:34
  • I have 4 pieces of data on each line which is separated by a "|", for example "name|image|price|link". Is it possible to only check the first piece of data which is "name" with the first piece of data already saved in the text file to make sure it is unique and they are not the same. – user3134976 Dec 26 '13 at 16:06