Credo che fgets è la risposta qui.
$handle = fopen($path, 'r+'); // open the file for r/w
while (!feof($handle)) { // while not end
$value = trim(fgets($handle)); // get the trimmed line
if ($value == $input) { // is it the value?
return; // if so, bail out
} //
} // otherwise continue
fwrite($handle, $input); // hasn't bailed, good to write
fclose($handle); // close the file
Questa risposta si basa unicamente sul fatto che si è aggiunto un ritorno a capo ("\n"
) nel codice, che è il motivo per cui fgets
funzionerà qui. Questo può essere preferibile rispetto a trascinare l'intero file in memoria con file_get_contents()
, semplicemente perché la dimensione del file potrebbe essere proibitiva.
In alternativa, se i valori non sono Newline delimitati, ma sono a lunghezza fissa, è sempre possibile utilizzare la $length
argomento fgets()
tirare esattamente $n
caratteri su (o usare fread()
per tirare esattamente $n
byte su)
Puoi chiarire di più il $ var – Ranjit
Ulteriori informazioni renderebbero più semplice rispondere a questa domanda. Il file è sempre delimitato da delimitazione? La lunghezza della stringa è fissa? Il file è piccolo (* fattibile per 'file_get_contents' *) o gargantuan? – Dan