Reading and Writing files, lines at a time
Moderator: General Moderators
-
Straterra
- Forum Regular
- Posts: 527
- Joined: Mon Nov 24, 2003 8:46 am
- Location: Indianapolis, Indiana
- Contact:
Reading and Writing files, lines at a time
I was wondering, how would I read a file (Lets say...test.txt). I would like to read the file line by line..I was wondering if this were possible. Also, I was wondering if it were possible to WRITE stuff to the text file 1 line at a time. Thanks.
The script below doesn't do what you want, but it is a great pointer towards what you want to do - and it's not difficult.
That is an example from the PHP manual entry for [php_man]file[/php_man]. I'd advise having a closer look, especially at the user notes. Most solutions are there. Takes a wee bit of effort though.
Code: Select all
<?php
// Get a file into an array. In this example we'll go through HTTP to get
// the HTML source of a URL.
$lines = file ('http://www.example.com/');
// Loop through our array, show html source as html source; and line numbers too.
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br>\n";
}
// Another example, let's get a web page into a string. See also file_get_contents().
$html = implode ('', file ('http://www.example.com/'));
?>- scorphus
- Forum Regular
- Posts: 589
- Joined: Fri May 09, 2003 11:53 pm
- Location: Belo Horizonte, Brazil
- Contact:
Use [php_man]fgets[/php_man]() to read a line from the pointer:
Cheers,
Scorphus.
Use [php_man]fwrite[/php_man]() to write to the pointer.[url=http://www.php.net/fgets]fgets[/url] section of the PHP Manual wrote:Code: Select all
<?php $handle = fopen ("/tmp/inputfile.txt", "r"); while (!feof ($handle)) { $buffer = fgets($handle, 4096); echo $buffer; } fclose ($handle); ?>
Cheers,
Scorphus.
-
Straterra
- Forum Regular
- Posts: 527
- Joined: Mon Nov 24, 2003 8:46 am
- Location: Indianapolis, Indiana
- Contact:
Thank you very much. I got the read code to work, but I am still a bit confused on the fwrite command. I wrote this counter program a long time ago..perhaps I could use some of its code to help me with the writing line by line?
Code: Select all
<?php
$val = file("counter.txt");
$num = $valї0];
$num++;
echo $num;
$fp = fopen( "counter.txt", "w" );
fwrite( $fp, $num );
?>- scorphus
- Forum Regular
- Posts: 589
- Joined: Fri May 09, 2003 11:53 pm
- Location: Belo Horizonte, Brazil
- Contact:
Sure!
. Explore the Manual, play around (my favourite learning way). Try hard! Then, let us know what you get or if you still have troubles.
Cheers,
Scorphus.
- Open a file for write with [php_man]fopen[/php_man]()
- Implement a [php_man]for[/php_man] loop to write each line to the file with [php_man]fwrite[/php_man]()
- Then close it with [php_man]fclose[/php_man]()
- [php_man]control-structures[/php_man]
- [php_man]filesystem[/php_man]
Cheers,
Scorphus.