카테고리 없음
CodeIgniter JSON 반환
광82
2023. 7. 11. 21:53
반응형
설명
코드이그나이터(CodeIgniter)로 서버를 만들고 할 때 JSON으로 반환 값을 출력해야하는 경우가 있습니다.
출력 클래스(Output Class)를 이용하여 뷰(View)말고 JSON 데이터를 반환하는 법을 알아보겠습니다.
출력 클래스에 대한 자세한 내용은 아래의 매뉴얼을 참조하시기 바랍니다.
- 출력(Output Class) : http://www.ciboard.co.kr/user_guide/kr/libraries/output.html
예제 코드는 제가 자주 사용하는 방식으로 작성했습니다.
▶JSON 반환 방법
예제는 컨트롤러(Controller)를 포함하여 작성하겠습니다.
기본 사용법
간단하게 배열(or 객체)을 JSON으로 출력해주는 매서드를 컨트롤러(Controller)에 추가해보겠습니다.
코드
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Json extends CI_Controller {
public function array_result()
{
$result = array(
array(
'name' => 'Edward',
'age' => 30
),
array(
'name' => 'Alex',
'age' => 25
)
);
$this->output->set_content_type('text/json');
$this->output->set_output(json_encode($result));
}
}
실행 결과 (/json/array_result)
[
{
"name": "Edward",
"age": 30
},
{
"name": "Alex",
"age": 25
}
]
응용 사용법
해당 컨트롤러(Controller)에 결과가 전부 JSON이면 remap을 이용하여 간단하게 처리할 수 있습니다.
코드
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Json extends CI_Controller {
public function _remap($method, $params=array())
{
if(method_exists($this, $method))
{
$result = call_user_func_array(array($this, $method), $params);
$this->output->set_content_type('text/json');
$this->output->set_output(json_encode($result));
}
else
{
return show_404();
}
}
public function array_result()
{
$result = array(
array(
'name' => 'Edward',
'age' => 30
),
array(
'name' => 'Alex',
'age' => 25
)
);
return $result;
}
public function array_result2()
{
$result = array(
array(
'name' => 'Jhon',
'age' => 27
),
array(
'name' => 'Tom',
'age' => 28
)
);
return $result;
}
// ... other method
}
실행 결과 (/json/array_result)
[
{
"name": "Edward",
"age": 30
},
{
"name": "Alex",
"age": 25
}
]
실행 결과 (/json/array_result2)
[
{
"name": "Jhon",
"age": 27
},
{
"name": "Tom",
"age": 28
}
]
반응형