php没有';t读取文本文件的内容


php doesn't read the contents of the text file

当我将php代码嵌入到html文件中以从同一目录中的文件中读取时,它不会在页面上显示任何内容。

  <html>
  <head>
   <title>Reading from text files</title>
  </head>
  <body>
   <?php
   $f = fopen("blah.txt", "r");
   echo fgets($f);                                      
   fclose($f); 
   ?>
 </body>
 </html>

如您的评论所示,我猜您需要首先安装PHP服务器。

最简单的方法是转到这个页面并为您的操作系统安装XAMPP,就像我假设的Windows一样。

安装后,所有的灯都是绿色的,或者至少PHP服务器打开你的浏览器并转到http://localhost,因为这应该会打开一个欢迎页面。

使用XAMPP,您的web根目录应该位于C:/xampp/htdocs/中,并将您的文件与index.phpblah.txt一起放在那里,它应该执行。因为index.php是默认打开的文件,所以刷新http://localhost会删除欢迎页面并加载脚本。

然而,也许这个代码比fopen:更容易使用

<?php
    if(file_exists($fname = './blah.txt')){
        echo file_get_contents($fname);
    } else {
        echo 'I should have known to set the correct path..';
    }
?>