title: Get response in JSON format in Yii2
body: <p>I'm trying to convert and array of response into JSON format. I have tried all the answers that were posted on SO and other websites like <a href="http://www.thecave.info/output-json-header-in-php/" rel="noreferrer">web1</a>,<a href="http://www.dyn-web.com/tutorials/php-js/json/array.php" rel="noreferrer">web2</a> adding <code>header('Content-Type: application/json')</code> and then <code>echo json_encode($data,JSON_PRETTY_PRINT);</code>
  But I'm always getting the output in text format.
  Can some one help me in solving this.</p>
  
  <p>Helpers Class:</p>
  
  <pre><code>public static function renderJSON($data) {
      header('Content-Type: application/json');
      echo json_encode($data,JSON_PRETTY_PRINT);
  }
  </code></pre>
  
  <p>My Controller:</p>
  
  <pre><code>if ($model-&gt;login()) {
      $user =  User::findByUsernameOrEmail($request-&gt;post('username'));
      $userArray = ArrayHelper::toArray($user);
      Helpers::renderJSON($userArray);
  </code></pre>
  
  <p>I tried to printing the <code>userArray</code> and it looks like this:</p>
  
  <pre><code>Array
  (
      [name] =&gt; abc
      [lastname] =&gt; xyz
      [username] =&gt; test_test
  )
  </code></pre>
  
  <p>Json output: (html/text)</p>
  
  <pre><code>{
      "name": "abc",
      "lastname": "xyz",
      "username": "test_test"
  }
  </code></pre>