Page 1 of 1
Reading and Writing files, lines at a time
Posted: Tue Dec 16, 2003 7:36 am
by Straterra
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.
Posted: Tue Dec 16, 2003 7:53 am
by patrikG
[php_man]file[/php_man] is your friend.
Posted: Tue Dec 16, 2003 7:55 am
by Straterra
I checked out file in the PHP Manual..and I got very quickly confused. Do you think you can give me a very simple example on how I would read and write to a specific line?
Posted: Tue Dec 16, 2003 8:03 am
by patrikG
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.
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/'));
?>
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.
Posted: Tue Dec 16, 2003 8:09 am
by scorphus
Use [php_man]fgets[/php_man]() to read a line from the pointer:
Use [php_man]fwrite[/php_man]() to write to the pointer.
Cheers,
Scorphus.
Posted: Tue Dec 16, 2003 8:20 am
by Straterra
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 );
?>
Posted: Tue Dec 16, 2003 8:52 am
by Straterra
Is there a way I can use the code from the post above to create a save program?
Posted: Tue Dec 16, 2003 11:05 am
by scorphus
Sure!
- 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]()
Follow these links:
- [php_man]control-structures[/php_man]
- [php_man]filesystem[/php_man]
Try to get it to work by yourself, you can do it

. 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.