【问题标题】:Write data in a view file in CodeIgniter在 CodeIgniter 的视图文件中写入数据
【发布时间】:2014-10-22 11:17:59
【问题描述】:

我正在尝试在 CodeIgniter 的视图文件中写入一些 JSON 数据。

但它显示错误:

Message: fopen() [function.fopen]: Filename cannot be empty

控制器功能如下:

public function write_in_a_view_file() {

    $data = array();
    $data['title'] = "Write This Title In a View File";

    $view_file = $this->load->view('result.php');

    $fp = fopen($view_file, 'w');
    fwrite($fp, json_encode($data));
    fclose($fp);

}

【问题讨论】:

  • 你真的 var_dump() $view_file 来检查它包含的内容吗?
  • Codeigniter load->view 函数是一个 void 函数,这意味着它不返回任何内容(或返回 NULL)。因此你不能 fopen NULL。也许您可以尝试从您的视图中加载 JSON 数据?或者将其作为字符串加载到您的控制器中,然后将其传递给您的视图。无论哪种方式都可以。
  • 是的,你为什么要在控制器操作中重写视图文件。 !?
  • 或者如果您的目标实际上是写入文件,那么您根本不需要使用视图。
  • @Ananth 我需要在一个新文件中写一些 json 代码

标签: php json codeigniter


【解决方案1】:

您可以为此使用 CodeIgniter File Helper。

public function write_in_a_view_file() {
    $data = array();
    $data['title'] = "Write This Title In a View File";

    $this->load->helper('file');
    $new_file_path = base_url() . '/path/to/file.php'; // modify this line to point to the actual location of the file
    write_file($new_file_path, json_encode($data));
}

【讨论】:

  • 公共函数 write_in_a_view_file() { $data = array(); $data['title'] = "将此标题写入视图文件"; $this->load->helper('file'); $new_file_path = base_url() 。 '公共/result.php'; write_file($new_file_path, json_encode($data)); }
【解决方案2】:

fopen 函数有 2 个参数,第一个参数必须是文件名,而第一个参数不传递任何内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 2014-02-14
    • 1970-01-01
    • 2015-04-20
    • 2013-07-10
    • 1970-01-01
    相关资源
    最近更新 更多