1

I am just trying to play with the new Codeiginiter4 framework. I have created one route & attached it to one simple method todos which is supposed to return a list of todos(task) as JSON when I try to hit the URL but it returns it as XML format. The code is simple,

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        return view('welcome_message');
    }

    public function todos()
    {   
        return $this->respondCreated(['todos' => ['task' => 'Check out new CI4']]);
    }

    //--------------------------------------------------------------------
}

// Result

<response>
<todos>
<task>Check out new CI4</task>
</todos>
</response>

Later I discovered that if I explicitly encode the array as JSON(using json_encode) it returns the result as JSON in the browser. Like this,

public function todos()
{   
    return $this->respondCreated(json_encode(['todos' => ['task' => 'Check out new CI4']]));
}

So my question is there a way to by default return array as JSON format in the browser in CI4?

CI Version I am using: v4.0.2

1 Answer 1

3

You're asking for an xml response so CI4 is giving you what you asked. You should define your http header to ask for json before you return your response.

public function todos()
    {   
       $this->request->setHeader('Accept', 'application/json');
        return $this->respondCreated(['todos' => ['task' => 'Check out new CI4']]);
    }

Note : if you always want json response you can go to app/Config/Format.php and comment out one line so your $supportedResponseFormats variable looks like this :

    public $supportedResponseFormats = [
        'application/json',
//      'application/xml', // machine-readable XML
        'text/xml', // human-readable XML
    ];

Problem is you're removing CI4 the ability to handle xml response this way.

Check out CI4 great documentation for more details : https://codeigniter.com/user_guide/outgoing/api_responses.html#handling-response-types

Sign up to request clarification or add additional context in comments.

1 Comment

Your solution works. I hade read the docs but it is not that much clearly mentioned I guess.

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.