10

I want to show response in json format in controller and don't want to move in view. So, please let me any way so that I can show json response.

Here is the code where i want to add json headers.

$result = $this->mod_doc->get_list();   
echo json_encode($result);

3 Answers 3

33

Just give these a try.

public function signin() {
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    

//add the header here
header('Content-Type: application/json');
echo json_encode( $arr );
}

or Try this way

return $this->output
        ->set_content_type('application/json')
        ->set_status_header(200) // Return status
        ->set_output(json_encode(array(your array)));
Sign up to request clarification or add additional context in comments.

3 Comments

only header('Content-Type: application/json'); worked for me
There is no need to change the header status to 500, this can be excluded set_status_header(500)
The second one is way much better than writing header eachtime Works smoothly
6
$result = $this->mod_doc->get_list();
$this->output
    ->set_content_type('application/json') //set Json header
    ->set_output(json_encode($result));// make output json encoded

for more reference https://codeigniter.com/userguide3/libraries/output.html

Comments

0

Source: https://www.codeigniter.com/user_guide/libraries/output.html?highlight=_output

$response = array('status' => 'OK');

$this->output
        ->set_status_header(200)
        ->set_content_type('application/json', 'utf-8')
        ->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
        ->_display();
exit;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.