Can I read a .TXT file with PHP?

前端 未结 6 909
遥遥无期
遥遥无期 2020-12-01 21:46

As I start the process of writing my site in PHP and MySQL, one of the first PHP scripts I\'ve written is a script to initialize my database. Drop/create the database. Dro

相关标签:
6条回答
  • 2020-12-01 21:59

    Well, since you're asking about resources on the subject, there's a whole book on it in the PHP.net docs.

    A basic example:

    <?php
    // get contents of a file into a string
    $filename = "/usr/local/something.txt";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    ?>
    
    0 讨论(0)
  • 2020-12-01 22:02

    From the PHP manual for fread():

    <?php
    // get contents of a file into a string
    $filename = "/usr/local/something.txt";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    ?>
    

    EDIT per the comment, you can read a file line by line with fgets()

    <?php
    $handle = @fopen("/tmp/inputfile.txt", "r");
    if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            echo $buffer;
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
    ?>
    
    0 讨论(0)
  • 2020-12-01 22:08

    file_get_contents does all that for you and returns the text file in a string :)

    0 讨论(0)
  • 2020-12-01 22:15

    All I need is a brief PHP example of how to open a TXT file on the server, read it sequentially, display the data on the screen, and close the file, as in this pseudo-code:

    echo file_get_contents('/path/to/file.txt');
    

    Yes that brief, see file_get_contents, you normally don't need a loop:

    $file = new SPLFileObject('/path/to/file.txt');
    foreach($file as $line) {
        echo $line;
    }
    
    0 讨论(0)
  • 2020-12-01 22:20

    Why you not read php documentation about fopen

     $file = fopen("source/file.txt","r");
      if(!file)
        {
          echo("ERROR:cant open file");
        }
        else
        {
          $buff = fread ($file,filesize("source/file.txt"));
          print $buff;
        }
    
    0 讨论(0)
  • 2020-12-01 22:21

    You want to read line by line? Use fgets.

    $handle = @fopen("myfile.txt", "r");
    if ($handle) {
        while (($content = fgets($handle, 4096)) !== false) {
            //echo $content;
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
    
    0 讨论(0)
提交回复
热议问题