在使用 CakePHP 3 生成XML输出时,我花了几个小时尝试解决以下问题。我试图在JSON和 XML 中公开Bookmarks Tutorial数据; JSON 视图在我使用时非常有效: /bookmarker/bookmarks.json 但是......当我尝试使用此网址时: /bookmarker/bookmarks.xml < / strong>我有这个回复:
此页面包含以下错误:
第6行第1行的错误:仅在文档开头允许XML声明 下面是第一个错误的页面呈现。
视图来源如下所示:
有人说这个错误是因为任何PHP 文件末尾都有一个空行。 我很确定我在中没有任何空白: AppController.php,routes.php和BookmarksController.php
1)我的 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)我的 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)在我的 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']);
}