For a school assignment I have to write a script in PHP. It has to create an array with names and write the array to a file. Then it has to delete the array, read the names in the file and the echo them.
This doesn't work:
<?php
$names = array("Name 1", "Name 2", "Name 3", "Name 4", "Name 5");
$filename = "names.txt";
$handle = fopen($filename, "wb+"); //open as read and write
$string = implode("\r\n", $names); //name on each line
fwrite($handle, $string); //write line
$names = array(); //empty array
print_r($names); //print empty array
$string = fread($handle, filesize($filename)); //read file
$names = explode("\r\n", $string); //lines to array
foreach ($names as $name) {
echo("<br>\n$name");
}
fclose($handle);
?>
But this works:
<?php
$names = array("Name 1", "Name 2", "Name 3", "Name 4", "Name 5");
$filename = "names.txt";
$handle = fopen($filename, "wb"); //open as write
$string = implode("\r\n", $names); //name on each line
fwrite($handle, $string); //write line
fclose($handle); //close
$handle = fopen($filename, "r"); //open as read
$names = array(); //empty array
print_r($names); //print empty array
$string = fread($handle, filesize($filename)); //read file
$names = explode("\r\n", $string); //lines to array
foreach ($names as $name) {
echo("<br>\n$name");
}
fclose($handle);
?>
I don't get why it works when I close and reopen the file. Any help would be appreciated.
All you need is to restart the file pointer because when using fwrite():
fwrite() writes the contents of string to the file stream pointed to by handle.
length bytes have been read
EOF (end of file) is reached
a packet becomes available or the socket timeout occurs (for network streams)
if the stream is read buffered and it does not represent a plain file, at most one read of up to a number of bytes equal to the chunk size (usually 8192) is made; depending on the previously buffered data, the size of the returned data may be larger than the chunk size.
if you look at fread()
fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the these conditions is met:
So at at the time you are calling fread($handle, filesize($filename)); you are already at the end of file therefore nothing would be displayed.
To resolve this just use fseek to restart the pointer back to the beginning of the file
Example :
fseek($handle, 0);
Yon't don't need to close the file .. your first code would work perfectly
Edit
You can also you rewind from PHP DOC
Sets the file position indicator for handle to the beginning of the file stream.
rewind($handle);
The second script is correct. The reason is that if you open a file for writing, you can not use to read, so you have to close the file and reopen it in read.
Related
Solved! I used an existing json file that I was using to display diagrams on the page.
I have a 2000 line text file. I want to read in the first 3000 bytes to a php variable. This works, but only at the cost of reading in the entire text file:
$little_diagrams = ('assets/diagrams.txt'); $mason = file($little_diagrams);
I tried this, but it doesn't work. Any ideas on why?
$little_diagrams = file_get_contents("assets/diagrams.txt", NULL, NULL, 0, 3000);
$mason = file($little_diagrams);
The trouble is that I have to process lines in "assets/diagrams.txt" such as:
2833|6979|Poloskov|||Nikolayev|Igor|2272|1n3rk1/3p1ppp/5q2/2p1P3/2B2P2/r2Q2P1/1b2N2P/1R3K1R|
2832|6979|Poloskov|||Nikolayev|Igor|2272|r2qk2r/1b1p1ppp/n4b2/2pN4/2B1P3/8/PP3PPP/R2QK1NR|
2831|6978|Nikolayev|Igor|2272|Buturin|Vladimir (IM)|2405|r3r1k1/1ppb1pp1/3p1n1p/2nP4/p3P3/4NP2/PPBN1KPP/R3R3|
2830|6978|Nikolayev|Igor|2272|Buturin|Vladimir (IM)|2405|r2qr1k1/1ppb1pp1/p1np1n1p/8/3PP3/4NN2/PPB2PPP/R2Q1RK1|
2829|6977|Nikolayev|Igor|2272|Tabatadze|Tamaz|2288|2rqk2r/4bp1p/p1n1b3/3pP3/Pp1P2p1/1P3p2/1B2NPPP/2RQNRK1|
2828|6976|Lutsko|Igor|2307|Nikolayev|Igor|2272|6r1/1pp2p1k/p2p3p/2bP4/2P2r2/1P4NP/P2R1P1K/5R2|
NEW CODE: (doesn't work, no diagrams are displayed at http://communitychessclub.com/ left column bottom)
$filename = "assets/diagrams.txt";
$handle = fopen($filename, "r");
$little_diagrams = fread($handle, 3000); //<<--- as per your need
fclose($handle);
$X = 5000; $line = 0;
foreach($little_diagrams as $line) {$X++; if ($X >= 5040) {break;} $token = explode("|", $line); //etc
}
<?php
$filename = "c:\\files\\yourfile.txt";
$handle = fopen($filename, "rb");
//$little_diagrams = fread($handle, filesize($filename));
$little_diagrams = fread($handle, 3000); //<<--- as per your need
fclose($handle);
?>
Try above code and read this fread function documentation
I hope this will help also see the example code Example #2 Binary fread() example
fread takes two arguments
string fread ( resource $handle , int $length )
second is length part
length bytes have been read as per documentation
fread() reads up to length bytes from the file pointer referenced by handle. Reading stops as soon as one of the following conditions is met:
UPDATED BELOW
Note:
You can use file_get_contents() to return the contents of a file as a string.
change second argument to FALSE from NULL then try hope it will work
so in my opinion correct code will be like below take a try
<?php
//however working with null also
$file_content =file_get_contents('demoTest.txt',FALSE,NULL,0,3000);
echo 'File Size: '.filesize('demoTest.txt');
echo '<br/> CONTENT HERE<br />'.$file_content;
echo '<br /><br />String Length: '.strlen($file_content);
?>
read the documentation at here for file function
english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt
I have an issue with writing and reading to text file.
I have to first write from a text file to another text file some values which I need to read again. Below are the code snippets:
Write to text file:
$fp = #fopen ("text1.txt", "r");
$fh = #fopen("text2.txt", 'a+');
if ($fp) {
//for each line in file
while(!feof($fp)) {
//push lines into array
$thisline = fgets($fp);
$thisline1 = trim($thisline);
$stringData = $thisline1. "\r\n";
fwrite($fh, $stringData);
fwrite($fh, "test");
}
}
fclose($fp);
fclose($fh);
Read from the written textfile
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
echo rtrim($kw[$i]);
}
But, if I am not mistaken due to the "/r/n" I used to insert the newline, when I am reading back, there are issues and I need to pass the read values from only the even lines to a function to perform other operations.
How do I resolve this issue? Basically, I need to write certain values to a textfile and then read only the values from the even lines.
I'm not sure whether you have issues with the even line numbers or with reading the file back in.
Here is the solution for the even line numbers.
$page = join("",file("text2.txt"));
$kw = explode("\n", $page);
for($i=0;$i<count($kw);$i++){
$myValue = rtrim($kw[$i]);
if(i % 2 == 0)
{
echo $myValue;
}
}
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 the foreach() 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 with fread(). Also, since $File is just a string variable, calling fclose() on it is unnecessary and doesn't do anything. You were correctly closing it by calling fclose() 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.
$file = '/var/apache2/htdocs/loginS/host.txt';
$content = file($file);
$save = fopen('./out.csv', 'w+');
foreach($content as $line) {
$line = rtrim($line, "\r\n"); // remove the newline from $line
$parts = explode("\t", $line);
$lineCsv = implode('|', $parts); // or ',' ?
fwrite($save, $lineCsv . "\n"); // write output to file
}
fclose($save);
I'm trying to read a specific line from a text file using php.
Here's the text file:
foo
foo2
How would I get the content of the second line using php?
This returns the first line:
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?>
..but I need the second.
Any help would be greatly appreciated
$myFile = "4-24-11.txt";
$lines = file($myFile);//file in to an array
echo $lines[1]; //line 2
file — Reads entire file into an array
omg I'm lacking 7 rep to make comments. This is #Raptor's & #Tomm's comment, since this question still shows up way high in google serps.
He's exactly right. For small files file($file); is perfectly fine. For large files it's total overkill b/c php arrays eat memory like crazy.
I just ran a tiny test with a *.csv with a file size of ~67mb (1,000,000 lines):
$t = -microtime(1);
$file = '../data/1000k.csv';
$lines = file($file);
echo $lines[999999]
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//227.5
//0.22701287269592
//Process finished with exit code 0
And since noone mentioned it yet, I gave the SplFileObject a try, which I actually just recently discovered for myself.
$t = -microtime(1);
$file = '../data/1000k.csv';
$spl = new SplFileObject($file);
$spl->seek(999999);
echo $spl->current()
."\n".(memory_get_peak_usage(1)/1024/1024)
."\n".($t+microtime(1));
//0.5
//0.11500692367554
//Process finished with exit code 0
This was on my Win7 desktop so it's not representative for production environment, but still ... quite the difference.
If you wanted to do it that way...
$line = 0;
while (($buffer = fgets($fh)) !== FALSE) {
if ($line == 1) {
// This is the second line.
break;
}
$line++;
}
Alternatively, open it with file() and subscript the line with [1].
I would use the SplFileObject class...
$file = new SplFileObject("filename");
if (!$file->eof()) {
$file->seek($lineNumber);
$contents = $file->current(); // $contents would hold the data from line x
}
you can use the following to get all the lines in the file
$handle = #fopen('test.txt', "r");
if ($handle) {
while (!feof($handle)) {
$lines[] = fgets($handle, 4096);
}
fclose($handle);
}
print_r($lines);
and $lines[1] for your second line
$myFile = "4-21-11.txt";
$fh = fopen($myFile, 'r');
while(!feof($fh))
{
$data[] = fgets($fh);
//Do whatever you want with the data in here
//This feeds the file into an array line by line
}
fclose($fh);
This question is quite old by now, but for anyone dealing with very large files, here is a solution that does not involve reading every preceding line. This was also the only solution that worked in my case for a file with ~160 million lines.
<?php
function rand_line($fileName) {
do{
$fileSize=filesize($fileName);
$fp = fopen($fileName, 'r');
fseek($fp, rand(0, $fileSize));
$data = fread($fp, 4096); // assumes lines are < 4096 characters
fclose($fp);
$a = explode("\n",$data);
}while(count($a)<2);
return $a[1];
}
echo rand_line("file.txt"); // change file name
?>
It works by opening the file without reading anything, then moving the pointer instantly to a random position, reading up to 4096 characters from that point, then grabbing the first complete line from that data.
If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:
$text = shell_exec("sed -n '74,159p' path/to/file.log");
This solution is good if your file is large.
You have to loop the file till end of file.
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
Use stream_get_line: stream_get_line — Gets line from stream resource up to a given delimiter
Source: http://php.net/manual/en/function.stream-get-line.php
You could try looping until the line you want, not the EOF, and resetting the variable to the line each time (not adding to it). In your case, the 2nd line is the EOF. (A for loop is probably more appropriate in my code below).
This way the entire file is not in the memory; the drawback is it takes time to go through the file up to the point you want.
<?php
$myFile = "4-24-11.txt";
$fh = fopen($myFile, 'r');
$i = 0;
while ($i < 2)
{
$theData = fgets($fh);
$i++
}
fclose($fh);
echo $theData;
?>
I like daggett answer but there is another solution you can get try if your file is not big enough.
$file = __FILE__; // Let's take the current file just as an example.
$start_line = __LINE__ -1; // The same with the line what we look for. Take the line number where $line variable is declared as the start.
$lines_to_display = 5; // The number of lines to display. Displays only the $start_line if set to 1. If $lines_to_display argument is omitted displays all lines starting from the $start_line.
echo implode('', array_slice(file($file), $start_line, lines_to_display));
I searched for a one line solution to read specific line from a file.
Here my solution:
echo file('dayInt.txt')[1]