如何在 codeigniter 中读取 .txt 或 .doc 文件?

How to read .txt or .doc file in codeigniter?

我正在尝试按照本教程进行操作 https://www.codeigniter.com/user_guide/helpers/file_helper.html 然后我让这个控制器显示我称之为 test.txt

的文件 txt 内容

class File_controller extends CI_Controller {
function __construct(){ 
parent::__construct();
        $this->load->helper('url'); 
            $this->load->helper('file');    
    }
public function index()
{
    $string = read_file(base_url().'test.txt');
    echo $string;
  }

 }

当我在浏览器中测试时没有发现错误,但是程序没有显示我的文件 txt 内容,所以

1.how 才能正确显示 test.txt?

2.what这个参数的意思是:

'./path/to/file.php'

当我使用

read_file('./path/to/file.php');

首先编辑您的项目index.php并将环境设置为开发,以便正确显示错误。您确实有一个错误,它只是通过此更改被抑制,它会向您显示您的错误。我认为第一个我可以发现自己 - php 函数实际上是 readfile() 而不是 read_file()。对于您的使用,我认为您会发现 file_get_contents() 效果更好。

关于你的文件路径。正如您拥有的那样,您的文本文件需要位于项目的根目录中,与您的 index.php 文件处于同一级别。它还需要可读。在开发模式下使用错误报告,如果路径或权限有任何问题,您将收到错误消息

如linkhttps://ellislab.com/codeigniter/user-guide/helpers/file_helper.html

中所述

Note: The path is relative to your main site index.php file, NOT your controller or view files. CodeIgniter uses a front controller so paths are always relative to the main site index.

这意味着

'./path/to/file.php'

将是您目录中相对于 index.php 的路径 假设您的主站点位于 "mysite" 文件夹中。所以 URL 可能是 http://localhost/mysite/ 并且假设文本文件 ('test.txt') 在主目录中。 因此,您现在将以

的形式访问此路径
read_file('/mysite/test.txt');

相应地,更改代码。

获取/设置文件内容

然后使用file_get_contents you可以检索文件的内容。

并使用 file_put_contents 您可以设置文件的内容。

您也可以查看