如何将json编码数据写入json文件?

时间:2015-06-11 11:22:19

标签: php json codeigniter

我正在尝试将json编码的数据放入json文件中以便在事件日历中显示它们。我正在使用php codeigniter framework.I只是想知道除了我使用的方法之外是否还有其他任何方法。因为它不起作用。但当我回显它显示的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);
    }

calendar_view

<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>

1 个答案:

答案 0 :(得分:1)

您可以使用 file_put_contents();

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