EvilZone
Programming and Scripting => Beginner's Corner => : Code.Illusionist December 08, 2014, 03:48:53 PM
-
Ok, let me tell you that I am newbie , but there is something that I don't quite understand. I do know how to open file, read from it. That's easy. BUT, when I add something, and then want to present file, before reading, and after reading , I have problem. Here is why. I tried doing this code:
<html>
<head>
</head>
<body>
<?php
if(file_exists("test.txt")) {
$fajl = fopen("test.txt","r");
echo "Fajl pre izmene: <br>";
while(!feof($fajl)) {
$read = fgets($fajl);
echo $read . "<br>";
}
fclose($fajl);
$fajl = fopen("test.txt","a+");
$add = "AOE = Area of effect";
fwrite($fajl,$add);
echo "Fajl nakon izmene:<br>";
while(!feof($fajl)) {
$read = fgets($fajl);
echo $read . "<br>";
}
fclose($fajl);
} else {
echo "Vas fajl ne postoji";
}
?>
</body>
</html>
test.txt file have:
BRB = Be right back
OMG = Oh my god
Now, I thought that , if I read file first, then close it, and then again open it for adding more into it, and after reading it, close it. It seems that first part of code works, but second one, do not. What can be the problem, all this seems bizzare to me.
-
You never reset the file pointer to the start of the file; I would suggest file_get_contents and file_put_contents... liek so
<?php
$file = "text.txt"
$filecontent = file_get_contents($file)
echo $filecontent
$filecontent .= "new stuff\n"
file_put_content($file,$filecontent)
$filecontent = file_get_contents($file)
echo $filecontent
?>
-
Okay, this do look more easier to work with. Just I have to learn how to use this function to print line by line.
-
$lines=explode("\n",$content);
\n depends on the format of the document.
-
Okay, this do look more easier to work with. Just I have to learn how to use this function to print line by line.
get everything from a file with file_get_contents, then explode the whole chunk with \r\n or whatever terminator you use, then loop through the array as if you were reading line by line.
fopen, fgets are only good for massive files, where you don't want everything to be put into memory.
-
Why something like this doesn't work?
<?php
$fileName = "test.txt";
$fileContent = file_get_contents($fileName);
$fileContent = explode($fileContent,"\n");
foreach($fileContent as $value) echo $value;
?>
EDIT: OK, I am idiot, I used explode function wrong...
This works:
<?php
$fileName = "test.txt";
$fileContent = file_get_contents($fileName);
$fileContent = explode("\n",$fileContent);
echo "Fajl pre ispravke:<br>";
foreach($fileContent as $key => $value) echo $value . "<br>";
array_push($fileContent, "AOE - Area of Effect");
echo "Fajl nakon ispravke <br>";
foreach($fileContent as $key => $value) echo $value . "<br>";
?>
EDIT2: I didn't actually changed file, i just changed string, but you know that xD