【问题标题】:php file read functionphp文件读取函数
【发布时间】:2012-08-03 13:08:16
【问题描述】:

我正在使用以下文件读取

$myFile = "file.txt";
$fh = fopen($myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

问题是 file.txt 是动态生成的并且在不同的文件夹中,所以我如何在 fopen 中调用它? 我正在尝试

$fh = fopen(/path/to/$myFile, 'r');

但显然它不起作用并给我错误

PHP Parse error:  syntax error, unexpected '/',

如何纠正这个问题并包含我的路径?

【问题讨论】:

  • "包围/path/to/$myFile
  • @PLB 它可以工作但进一步给我错误 PHP 警告:filesize() [function.filesize]: stat failed and PHP Warning: fread () [function.fread]: 长度参数必须大于0
  • 确保使用fread("/path/to/$myFile")

标签: php file-read


【解决方案1】:

这是一种更简单的方法:

$theData = file_get_contents("/path/to/file/" . $myFile);

【讨论】:

  • 它有效但进一步给我错误 PHP 警告:filesize() [function.filesize]: stat failed and PHP Warning: fread() [function.fread]:长度参数必须大于0 – user1561466刚刚编辑
  • 通过这种方式,您无需打开文件、统计它和所有其他内容,只需一条命令即可返回文件内容。
【解决方案2】:

首先,使用file_get_contents()会更简单

至于文件路径,需要为字符串,即:

$fh = fopen("/path/to/".$myFile, 'r');

【讨论】:

  • 对于简单的字符串总是使用单引号,你永远不必担心转义......
  • @inVader 错误。 $myStr = 'Matt\'s string';
  • @Matt - 对,是的......但是,如果您没有变量或特殊字符,单引号是可行的方法。
  • @inVader 同意。我只是指出可能会使新手感到困惑的信息。
  • 单引号在 PHP 中也更快,因为它不必为变量解析它们。
【解决方案3】:
$myPath = "/path/to/file/";
$myFile = "file.txt";
$fh = fopen($myPath.$myFile, 'r');
$theData = fread($fh, filesize($myFile));
fclose($fh);
echo $theData;

我还没有测试过,但我想它会这样工作......

【讨论】:

  • 它有效但进一步给我错误 PHP 警告:filesize() [function.filesize]: stat failed and PHP Warning: fread() [function.fread]:长度参数必须大于0
  • 你必须把第4行改成$theData = fread($fh, filesize($myPath.$myFile));
【解决方案4】:

我试图以自己的方式解决这个问题。希望这会对你有所帮助。

<?php

$myFile = "folder/file.txt";
$myHandle = fopen($myFile, "r");

$myData = fread($myHandle, filesize($myFile));
$rows = explode(" ", $myData);

foreach($rows as $row) 
{
    print $row;
}

fclose($myHandle);

?> 

【讨论】:

    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-16
    • 1970-01-01
    • 2011-02-08
    • 1970-01-01
    相关资源
    最近更新 更多