Respond as XML not working since cakePHP 3.1

梦想与她 提交于 2019-11-28 10:33:19

问题


I need to render an XML+XSL template in my application, and it used to work with cakePHP 3.0. I have made the switch to 3.1 recently and it has stopped working. The problem is that I was having a formatted view of my XML, while now I just get a plain string.

The migration guide says something about some changes in the RequestHandlerComponent, but nothing helpful (or maybe it's just me and I don't get the point :)).

This is my controller (it is exactly as it was with Cake3.0):

<?php
namespace App\Controller;

use App\Controller\AppController;
use Cake\Utility\Xml;
use Cake\Event\Event;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry;
use Cake\Filesystem\Folder;
use Cake\Filesystem\File;
use Cake\Network\Email\Email;
use Cake\Core\Configure;
use Cake\I18n\Time;

/**
 * Invoices Controller
 *
 * @property App\Model\Table\InvoicesTable $Invoices
 */
class InvoicesController extends AppController
{
    public $components = [
        'Browser',
        'Reorder11'
    ];
    public $helpers = [
        'Multiple'
    ];
    public $paginate = [];

    public function initialize()
    {
        parent::initialize();
        $this->loadComponent('Paginator');
        $this->loadComponent('RequestHandler');
    }

    public function beforeFilter(Event $event)
    {
        parent::beforeFilter($event);
        $this->Auth->allow(['demo']);
    }

    /*
    * ... several other functions ...
    */

    public function viewxml($id = null)
    {
        $this->viewBuilder()->layout('xml');
        $invoice = $this->Invoices->myInvoice($id, $this->Auth->user('id'));

        $this->RequestHandler->respondAs('xml');
        $this->set('invoice', $invoice);
    }
}

The xml.ctp layout, which is really simple

echo $this->fetch('content');

and the viewxml.ctp template just echoes the xml as a string.

How can I obtain the formatted XML+XSL again?


回答1:


Try add: $this->response->header(['Content-type' => 'application/xml']);

I had the same error but my output was pdf

working 3.0.14 using this code:

$this->RequestHandler->respondAs("pdf");
$this->layout = 'pdf/default';
$this->view = 'pdf/report1_pdf';

for 3.1.x (this works if u save the file and open later, if you try to open it directly on browser its print the plain file content as a txt/html):

$this->viewBuilder()->layout('pdf/default');
$this->viewBuilder()->template('pdf/report1_pdf');
$this->RequestHandler->respondAs('pdf');
$this->response->header(['Content-type' => 'application/pdf']);


来源:https://stackoverflow.com/questions/32757870/respond-as-xml-not-working-since-cakephp-3-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!