file read problem

Discussion in 'PHP' started by mirosoft1, Feb 5, 2008.

  1. #1
    i have a text file include two lines
    line 1
    line 2

    i know how to read the first line
    with this code

    <?php
    $myFile = "test.txt";
    $fh = fopen($myFile, 'r');
    $theData = fgets($fh);
    fclose($fh);
    echo $theData;

    ?>
    but i canot read the second line
    please help me on this
     
    mirosoft1, Feb 5, 2008 IP
  2. powerspike

    powerspike Peon

    Messages:
    312
    Likes Received:
    10
    Best Answers:
    0
    Trophy Points:
    0
    #2
    try this
    
    $filename = "file.txt";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    $data = explode("\n",$contents);
    for($i=0,$b=sizeof($data);$i<$b;$i++)
    {
    print $data[$i];
    }
    
    PHP:
    $data becomes an array where each piece is a line of the text file.
    so there there are 20 lines in the text file, the array will have 20 pieces in it.
     
    powerspike, Feb 5, 2008 IP
  3. mirosoft1

    mirosoft1 Well-Known Member

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #3
    but this code read all the file , i want the secont line olnly
     
    mirosoft1, Feb 5, 2008 IP
  4. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #4
    Use fgets again. Each time you use that it will read the next line in the file.

    Unless you know the position of the \n in the file, fgets is the easiest method to get a specific line.
     
    joebert, Feb 5, 2008 IP
  5. mirosoft1

    mirosoft1 Well-Known Member

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #5
    can you tell me the code because i feel bother i canot understand how?
     
    mirosoft1, Feb 5, 2008 IP
  6. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #6
    <?php
    $myFile = "test.txt";
    
    $fh = fopen($myFile, 'r');
    
    $line1 = fgets($fh);
    $line2 = fgets($fh);
    
    fclose($fh);
    
    echo "Line 1: $line1";
    echo "Line 2: $line2";
    ?>
    PHP:
     
    joebert, Feb 5, 2008 IP
  7. mirosoft1

    mirosoft1 Well-Known Member

    Messages:
    110
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    101
    #7
    yes it works thank you but i want to take the first line but the value on another variable how i do this?
     
    mirosoft1, Feb 5, 2008 IP
  8. joebert

    joebert Well-Known Member

    Messages:
    2,150
    Likes Received:
    88
    Best Answers:
    0
    Trophy Points:
    145
    #8
    I'm not sure what you want to do.
     
    joebert, Feb 5, 2008 IP