Vladimir Shabuniayeu
Vladimir Shabuniayeu

Reputation: 147

How in one controller return HTML or JSON(PHP)

I have a Yii site with 2 pages site.com/user/create and site.com/user/create.json

I need to have one controller for both pages.

  1. How do I make a route for these - I tried <controller:\w+>/<action:\w+>.json'=>'<controller>/<action>) but it didn't help
  2. How do I identify in controller whether the request is for JSON or HTML - I have tried $_SERVER['CONTENT_TYPE'], in the REST client it was OK, but in the browser I got a PHP notice Undefined index: CONTENT_TYPE

Upvotes: 1

Views: 722

Answers (1)

Ansari
Ansari

Reputation: 8218

There are at least 2 ways of doing it:

  1. Yii::app()->request->getRequestUri(); will get you the request URI - check it for the .json extension at the end. The routing rule you have in your question should work and get the request to the right controller and action.
  2. You can make a routing rule like this:

    <controller:\w+>/<action:\w+>.json'=>'<controller>/<action>/format/json
    

    and then check for the format parameter inside your action.

I suggest the second way since it's extendable.

Upvotes: 2

Related Questions