Use fopen($file,'w')
(why do you want to write in the file also correct!?) (if it is read only, use "a"):
function lerFicheiro(){
$rec = array();
$file = './receitas.txt';
$fh=fopen($file,'w') or die ('Nao foi possivel abrir o ficheiro!');
$data = fread($fh, filesize($file)) or die ('Nao foi possivel abrir o ficheiro!');
fclose($fh);
$regReceita = explode("\n", $data);
foreach ($regReceita as $item){
$registo=explode(";", $item);
if (count($registo) > 1) {
$rec[] = array('receita' => $registo[0], 'descricao' => $registo[1]);
}
}
return $rec;
}
Options:
'r' - Opens only for reading; puts the pointer at the beginning of the file.
'r +' - Opens for reading and writing; puts the pointer at the beginning of the file.
'w' - Opens only for recording; puts the pointer at the beginning of the file and erases the content that has already been written. If the file does not exist, try to create it.
'w +' - Opens for reading and writing; puts the pointer at the beginning of the file and erases the content that has already been written. If the file does not exist, try to create it.
'a' - Opens the file for writing only; puts the pointer at the end of the file. If the file does not exist, try to create it.
'a +' - Opens the file for reading and writing; puts the pointer at the end of the file. If the file does not exist, try to create it.
I have tried this here is the error that appears to me -imgur.com/a/7XZvr - Megaluk
Check the file size before fread()
:
if(filesize($file) > 0)
-
function lerFicheiro(){
$rec = array();
$file = './receitas.txt';
$fh=fopen($file,'w') or die ('Nao foi possivel abrir o ficheiro!');
if(filesize($file) > 0) {
$data = fread($fh, filesize($file)) or die ('Nao foi possivel abrir o ficheiro!');
} else {
echo 'Arquivo vazio';
$data = "";
}
fclose($fh);
$regReceita = explode("\n", $data);
foreach ($regReceita as $item){
$registo=explode(";", $item);
if (count($registo) > 1) {
$rec[] = array('receita' => $registo[0], 'descricao' => $registo[1]);
}
}
return $rec;
}