【问题标题】:How to write json encoded data into a json file?如何将json编码的数据写入json文件?
【发布时间】:2015-08-27 01:35:02
【问题描述】:

我正在尝试将 json 编码数据放入 json 文件中,以便在事件日历中显示它们。我正在使用 php codeigniter 框架。我只想知道除了我使用的方法之外是否还有其他方法。因为它不工作。但是当我回显它显示的json_encode 数据时。但我想将它们写入一个单独的文件调用events.json

提前致谢。

型号

function get_all_reservations_for_calendar(){
        $this->db->select('reservations.date,reservations.time,reservations.hall');
        $this->db->from('reservations');
        $this->db->where('is_deleted', '0');
        $query = $this->db->get();
        return $query->result();
    }

控制器

function index() {
        $reservation_service = new Reservation_service();
        $output['calendar_results'] = $reservation_service->get_all_reservations_for_calendar();
        $partials = array('content' => 'dashboard/dashboard_view');
        $this->template->load('template/main_template', $partials, $output);
    }

日历视图

<head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <style type="text/css">
            #event_cal{
                width: 500px;
                height: 500px;
            }
        </style>

        <link rel="stylesheet" href="http://localhost/Calendar/backend_resources/css/eventCalendar.css">
        <link rel="stylesheet" href="http://localhost/Calendar/backend_resources/css/eventCalendar_theme_responsive.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
        <script src="http://localhost/Calendar/backend_resources/js/jquery.eventCalendar.min.js" type="text/javascript"></script>

        <?php //echo json_encode($calendar_results); ?>
        <?php
        //write to json file
        $fp = fopen('events.json', 'w');
        fwrite($fp, json_encode($calendar_results));
        fclose($fp);
        ?>

        <script type="text/javascript">
            $(function() {
                $("#event_cal").eventCalendar({
                    eventsjson: 'http://localhost/Calendar/backend_resources/json/events.json',
                    dateFormat: 'dddd MM-D-YYYY'
                });
            });
        </script>
    </head>
    <body>
        <div id="event_cal" ></div>
    </body>
</div>

【问题讨论】:

  • 也许这个堆栈溢出帖子可能会对您有所帮助。 write json encoded values into a file
  • 您也可以在控制器内部执行此操作,将其写入文件的过程。因为您不必将 php 和 html 混合在一起。
  • fwrite()的返回值是多少?
  • @Harigovind R 谢谢。我会参考的。
  • 所以701字节被成功写入文件。您需要更准确地指定究竟是什么不起作用。

标签: php json codeigniter


【解决方案1】:

您可以使用 file_put_contents();

放置文件数据
<?php
    //write to json file
     $jsonEvents=json_encode($calendar_results);
     file_put_contents('events.json',$jsonEvents);
    ?>

【讨论】:

猜你喜欢
  • 2018-03-27
  • 2012-08-31
  • 2019-09-22
  • 1970-01-01
相关资源
最近更新 更多