PHP: 我的文本文件只有在我添加包含函数时才会被读取
PHP: My text file only gets read when I add include function
我是 PHP 的新手,目前正在研究文件处理。我有一个文本文件,我正尝试使用框架脚本为 reading/appending 打开该文件。该文件正在输出并显示它已成功打开,但只有当我将包含函数添加到代码中时。我的代码在下面,有人可以看看它并告诉我我做的是否正确,因为当时我觉得它是正确的并且它确实输出但我不是 100% 积极的。
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
include($location);
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} else {
echo 'File not found';
}
将您的代码更改为读取和输出文件如下:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
//include($location); remove include
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
echo $file_content; //<----echo here to display content
fclose($file);
} else {
echo 'File not found';
}
另一种选择是使用 file_get_contents()。
它还会读取文本文件,但会将文本文件的全部内容读取为字符串。
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location)){
$file_content = file_get_contents($file);
Echo $file_content;
$file_content .= " And some more"; //append string to end of string
Echo $file_content; // echo with appended string.
File_put_contetnts($file, $file_content); // save the original text plus the appended.
} else {
echo 'File not found';
}
我是 PHP 的新手,目前正在研究文件处理。我有一个文本文件,我正尝试使用框架脚本为 reading/appending 打开该文件。该文件正在输出并显示它已成功打开,但只有当我将包含函数添加到代码中时。我的代码在下面,有人可以看看它并告诉我我做的是否正确,因为当时我觉得它是正确的并且它确实输出但我不是 100% 积极的。
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
include($location);
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
fclose($file);
} else {
echo 'File not found';
}
将您的代码更改为读取和输出文件如下:
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
//include($location); remove include
if (file_exists($location) && $file = fopen($location, 'r')){
$file_content = fread($file, filesize($location));
echo $file_content; //<----echo here to display content
fclose($file);
} else {
echo 'File not found';
}
另一种选择是使用 file_get_contents()。
它还会读取文本文件,但会将文本文件的全部内容读取为字符串。
$location = '/Applications/MAMP/htdocs/PHPLabs/branches.txt';
if (file_exists($location)){
$file_content = file_get_contents($file);
Echo $file_content;
$file_content .= " And some more"; //append string to end of string
Echo $file_content; // echo with appended string.
File_put_contetnts($file, $file_content); // save the original text plus the appended.
} else {
echo 'File not found';
}