【PHP框架CodeIgniter学习】使用辅助函数—建立自己的JSONHelper
本文使用的是2.1.4版本,看的时候请注意。
官方文档:http://codeigniter.org.cn/user_guide/general/helpers.html(关于辅助函数Helper的使用)
一、辅助函数是什么
辅助函数,顾名思义,是帮助我们完成特定任务的函数。每个辅助函数文件仅仅是一些函数的集合。例如,URL Helpers 可以帮助我们创建链接,Form Helpers 可以帮助我们创建表单,Text Helpers 提供一系列的格式化输出方式,Cookie Helpers 能帮助我们设置和读取COOKIE,File Helpers 能帮助我们处理文件,等等。
二、怎么新建辅助函数
打开application\helpers目录,新建json_helper.php;
因为PHP自带的json_encode 对中文的封装不是很好,会出现\u5c3c\u739b这种诡异的想象,那么我们想要的目的是输出中文,所以就写一个辅助函数来自己调用;
内容:
12345678910111213141516171819202122232425262728<?php
class
UserController
extends
CI_Controller
{
public
function
__construct()
{
parent::__construct();
$this
->load->helper(
'json'
);
$this
->output->set_content_type(
'application/html;charset=utf-8'
);
}
function
index()
{
$this
->load->model(
'user_model'
);
$data
[
'result'
] =
$this
->user_model->get_last_ten_entries();
$data
[
'title'
] =
'Hello World Page Title'
;
$this
->load->view(
'user_view'
,
$data
);
}
function
toJson()
{
$this
->load->model(
'user_model'
);
$data
[
'result'
] =
$this
->user_model->get_last_ten_entries();
$data
[
'title'
] =
'Hello World Page Title'
;
$rs
= mJson_encode(
$data
[
'result'
]);
echo
$rs
;
}
}
?>