【问题标题】:PHP: How do I display the contents of a textfile on my page?PHP:如何在我的页面上显示文本文件的内容?
【发布时间】:2011-06-12 20:49:42
【问题描述】:

我的网络服务器(本地)上有一个 .txt 文件,并希望通过 PHP 回显显示页面中的内容(存储在同一服务器上)。

.txt 文件包含一个由另一个页面上的另一个脚本更新的数字,但对于这个页面,我只想从文件中提取数字/txt 文件内容并回显它(以保存必须执行的页面再次获取数字所涉及的计算)。

我该怎么做?

这是我目前得到的:

    <?php
    $myFile = "http://renownestates.com/cache/feedSubscribers.txt";
    $fh = fopen($myFile, 'r');
    $theData = fread($fh, 1);
    fclose($fh);
    echo $theData;
    ?>     

【问题讨论】:

    标签: php echo


    【解决方案1】:

    在这里,试试这个(假设它是一个小文件!):

    <?php
    echo file_get_contents( "filename.php" ); // get the contents, and echo it out.
    ?>
    

    文档是here

    【讨论】:

    • 这段代码 sn-p 是否包含在 WordPress 主题的侧边栏中是否重要? ..ive 替换了'filename.php。使用 'www.domain.com/myfile.txt' 并且它不起作用:(
    • 啊,我现在开始工作了!取出网址,然后去了../fileLocation。谢谢!!!! :D
    【解决方案2】:

    如果只是读取文件并输出它,最好的方法是readfile

    【讨论】:

    • 这将返回文件的字节,而不是内容
    【解决方案3】:

    我必须使用 nl2br 来正确显示回车,它对我有用:

    <?php
    echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
    ?>
    

    【讨论】:

    • 以上也可以用于.txt文件。
    【解决方案4】:

    如果你不想对文件中的内容做任何事情,只需显示它,你实际上可以include() 它。 include 适用于任何文件类型,但它当然会运行它在其中找到的任何 php 代码。

    【讨论】:

      【解决方案5】:

      我必须显示计算机代码文件。如果文件中包含小于或大于等特殊字符,则简单的“包含”将不会显示它们。试试:

      $file = 'code.ino';
      $orig = file_get_contents($file);
      $a = htmlentities($orig);
      
      echo '<code>';
      echo '<pre>';
      
      echo $a;
      
      echo '</pre>';
      echo '</code>';
      

      【讨论】:

        【解决方案6】:
        <?php
        $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
        echo fread($myfile,filesize("webdictionary.txt"));
        fclose($myfile);
        ?>
        

        试试这个在php中打开一个文件

        请参考:(http://www.w3schools.com/php/showphp.asp?filename=demo_file_fopen)

        【讨论】:

          【解决方案7】:

          如果您只想显示文件本身:

          header('Content-Type: text/plain');
          header('Content-Disposition: inline; filename="filename.txt"');
          readfile(path);
          

          【讨论】:

            【解决方案8】:

            使用 PHP 的fopen

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-08-21
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-07-06
              • 1970-01-01
              相关资源
              最近更新 更多