I have spent some hours trying to fix following issue when generating an XML output using CakePHP 3. I am trying to expose the Bookmarks Tutorial data in JSON and XML; JSON view works perfectly when I use: /bookmarker/bookmarks.json but... when I try to use this URL: /bookmarker/bookmarks.xml I have this response:
This page contains the following errors:
error on line 1 at column 6: XML declaration allowed only at the start of the document Below is a rendering of the page up to the first error.
The view source looks like this:
Some people says this error is because of a blank line at the end of any PHP file. I am pretty sure I don't have any blank line in: AppController.php, routes.php and BookmarksController.php
This is my configuration:
1) My routes.php
Router::scope('/', function ($routes) {
// Connect the default routes.
$routes->fallbacks('InflectedRoute');
// This allows us to have a RESTful Route for BookmarksController
$routes->extensions(['json', 'xml']);
$routes->resources('Bookmarks');
$routes->resources('Tags');
});
2) My BookmarksController.php
public function index()
{
$this->paginate = [
'contain' => ['Users'],
'conditions' => [
'Bookmarks.user_id' => $this->Auth->user('id'),
]
];
$this->set('bookmarks', $this->paginate($this->Bookmarks));
$this->set('_serialize', ['bookmarks']);
}
3) In my AppController.php
public function initialize()
{
parent::initialize();
$this->loadComponent('Flash');
// Component to enable REST responses
$this->loadComponent('RequestHandler');
$this->loadComponent('Auth', [
'authorize' => 'Controller', // We will be creating a custom autorization method (see isAuthorized() bellow)
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email',
'password' => 'password'
]
]
],
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'unauthorizedRedirect' => $this->referer()
]);
// Allow the display action so our pages controller
// continues to work.
$this->Auth->allow(['display']);
}