Re: Overwriting/updating textfile data - halfworking

Hiya,

I seemed to have a problem to try update my data kept in a textfile with the following code:

[code]
<?php

$filename = "months.txt";
$rowToUpdate = 2;
$newString = "This text is updated
";

$arrFp = file( $filename );

$arrFp[$rowToUpdate] = $newString;
$numLines = count( $arrFp );

$fp = fopen( $filename, "w" );

for($i=0; $i<$numLines; $i++)
{
fwrite($fp, $arrFp[$i]);
}

fclose( $fp );

print "updated!!!";

?>
[/code]

My textfile simply contained:
10
11
12
13
14
15

What happened is that, everytime the codes are executed, it would update the row, then it would leave any rows after that blank in my textfile, like:
10
11
This text is updated.
(then blank the rest of the file)

What could be the problem? Theoretically, it should be able to loop pass the row to be updated, and just re-write the original values into the file, right?

Please help! Thanks in advance!

Comments

  • [b][red]This message was edited by tvienti at 2005-5-3 0:10:3[/red][/b][hr]
    That's odd. It looks good to me. I have two tests I want you to run, to try isolating the problem.

    First, add the red line below right after the numLines assignment

    [code]
    $numLines = count( $arrFp );
    [red]echo "numLines is $numLines
    ";[/red]
    [/code]

    Second, try commenting out the line

    [code]$arrFp[$rowToUpdate] = $newString;[/code]

    So that in essence you're just reading the lines in, and printing them back out. The file shouldn't be visibly changed after execution. Try running that and see if it works.. let me know what output you get.

    T

    : Hiya,
    :
    : I seemed to have a problem to try update my data kept in a textfile with the following code:
    :
    : [code]
    : <?php
    :
    : $filename = "months.txt";
    : $rowToUpdate = 2;
    : $newString = "This text is updated
    ";
    :
    : $arrFp = file( $filename );
    :
    : $arrFp[$rowToUpdate] = $newString;
    : $numLines = count( $arrFp );
    :
    : $fp = fopen( $filename, "w" );
    :
    : for($i=0; $i<$numLines; $i++)
    : {
    : fwrite($fp, $arrFp[$i]);
    : }
    :
    : fclose( $fp );
    :
    : print "updated!!!";
    :
    : ?>
    : [/code]
    :
    : My textfile simply contained:
    : 10
    : 11
    : 12
    : 13
    : 14
    : 15
    :
    : What happened is that, everytime the codes are executed, it would update the row, then it would leave any rows after that blank in my textfile, like:
    : 10
    : 11
    : This text is updated.
    : (then blank the rest of the file)
    :
    : What could be the problem? Theoretically, it should be able to loop pass the row to be updated, and just re-write the original values into the file, right?
    :
    : Please help! Thanks in advance!
    :



Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

In this Discussion