Space being added while reading lines from a file

Discussion in 'PHP' started by siber, Nov 20, 2007.

  1. #1
    Hi,

    When running the script given below, while displaying the contents of the file "user_names.txt" I see a space being added at the end of each line. Due to this my condition statement is showing an incorrect result. Could someone please help me to resolve this issue? I have tried running this script on both windows and linux servers.

    Thanks.

    --------------------------------
    <?php
    $uid = "user_1";

    $uidFile = "user_names.txt";
    $uidFileHeader = @fopen($uidFile, 'r');
    if ($uidFileHeader) {
    while (!feof($uidFileHeader)) {
    $reserved_names = fgets($uidFileHeader);
    print "res $reserved_names*<P>";
    print "uid $uid*<P>";
    if ($reserved_names == $uid){
    print "Got one<P>";
    }
    }
    fclose($uidFileHeader);
    }
    ?>
    -------------------------
    The output:

    res user_1 *
    uid user_1*
    res user_2 *
    uid user_1*
    res user_3 *
    uid user_1*
    res *
    uid user_1*

    --------------------------
    Content of "user_names.txt"

    user_1
    user_2
    user_3
     
    siber, Nov 20, 2007 IP
  2. commandos

    commandos Notable Member

    Messages:
    3,648
    Likes Received:
    329
    Best Answers:
    0
    Trophy Points:
    280
    #2
    you can use the trim function to remove the white spaces ...
     
    commandos, Nov 20, 2007 IP
    tarponkeith likes this.
  3. TwistMyArm

    TwistMyArm Peon

    Messages:
    931
    Likes Received:
    44
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Yeah, if you actually view the source of the outputted HTML, you'll probably not see a space before the <p> but in fact a new line (which is converted to a space by browsers). Hence the reason to use trim.
     
    TwistMyArm, Nov 20, 2007 IP
  4. siber

    siber Peon

    Messages:
    8
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Thanks a lot. It worked.

    I replaced the line "$reserved_names = fgets($uidFileHeader);" with "$reserved_names = trim(fgets($uidFileHeader));"
     
    siber, Nov 20, 2007 IP