I am very new to php, and i have search and put together this script to convert text to csv and write the out put on the file.
$File = "/var/apache2/htdocs/loginS/host.txt";
$Handle = fopen($File,"r");
$Content = fread ($Handle,filesize ($File));
fclose($File);
fclose($Handle);
$Content = explode("\t", $Content);
foreach($Content as $Value) {
//echo $Value."|"; // till this line working
fwrite($save, $Value);
fclose($save);
}
the problem is when I try to write on the file. I got only one line.what is my error.
You are calling
fclose()on the file in your loop that is writing records.fclose()closes the file handle so it is no longer valid and cannot be written to.Move
fclose($save);after the}that ends theforeach()with your content.Also, you could simplify things a bit by calling
$Content = file_get_contents($File);since that is what you are doing in effect withfread(). Also, since$Fileis just a string variable, callingfclose()on it is unnecessary and doesn’t do anything. You were correctly closing it by callingfclose()on$Handle. But using file_get_contents() will eliminate the need for both. The only file you would need is the one you were writing to.Here is an example using the file() function which reads each line of a file into an array.