简体   繁体   English

PHP打开txt文件并回显其内容

[英]PHP open txt file and echo its contents

The path of my .txt file is C:\\Users\\George\\Desktop\\test.txt 我的.txt文件的路径是C:\\Users\\George\\Desktop\\test.txt

And I use: 我用:

$path = "C:\\Users\\George\\Desktop\\test.txt";
$fileContent = file_get_contents($path);
echo $fileContent;

But I get file_get_contents(C:\\Users\\George\\Desktop\\test.txt) [function.file-get-contents]: failed to open stream . 但是我得到了file_get_contents(C:\\Users\\George\\Desktop\\test.txt) [function.file-get-contents]: failed to open stream But why? 但为什么?

Use this code: 使用此代码:

$path = "C:/Users/George/Desktop/test.txt";
$fileContent = file_get_contents($path);
echo $fileContent;

as the error mentions, that path exists... 如错误所述,该路径存在...

Wrong assertion, PHP is just telling you there was an error opening that path, it doesn't mean it exists, also, the error message should mention the reason for the error, ie: not found , permission denied , etc... 错误的断言,PHP只是告诉您打开该路径存在错误,并不意味着它存在,而且,错误消息中应提及错误原因,即: not foundpermission denied等。


Answer: 回答:

Your code syntax is correct. 您的代码语法正确。 The error is one of the following 3: 该错误是以下之一:

1 - The file doesn't exist. 1-该文件不存在。
2 - The path is wrong. 2-路径错误。
3 - Php doesn't have permission to access that file. 3-Php无权访问该文件。

Maybe if YOU do not have the right to read this file as PHP, the system have it, try exec or system : 也许如果您无权以PHP读取此文件,则系统拥有它,请尝试exec或system:

$path = 'C:\\Users\\George\\Desktop\\test.txt';

function getFile_exec($path)
{
    if(file_exists($path))
    {
        return exec("cat $path");
    }
    else
    {
        return false;
    }
}

function getFile_syst($path)
{
    if(file_exists($path))
    {
        return system("cat $path");
    }
    else
    {
        return false;
    }
}

var_dump(getFile_exec($path));
var_dump(getFile_syst($path));

But as you have this error : Warning: file_get_contents(C:/Users/George/Desktop/test.txt) [function.file-get-contents]: failed to open stream: No such file or directory in /home/a2133027/public_html/index.php on line 5 and like Pedro Lobito said, you must be on linux, so, the good way to access your files on desktop may be : ~/Desktop/test.txt or ~/test.txt if it's directly in your user files ... Are you sure, you are under windows ? 但是由于出现此错误: Warning: file_get_contents(C:/Users/George/Desktop/test.txt) [function.file-get-contents]: failed to open stream: No such file or directory in /home/a2133027/public_html/index.php on line 5就像Pedro Lobito所说,您必须在linux上,因此,在桌面上访问文件的好方法可能是: ~/Desktop/test.txt~/test.txt如果直接使用)在您的用户文件中...您确定您在Windows下吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM