CakePHP 3 creating XML view

女生的网名这么多〃 提交于 2019-12-12 04:06:23

问题


I need to convert an array to an XML response. The objective is to write a function within a plugin controller and call it, which would return an XML response.

I've been trying this below mentioned code from the CakePHP manual.

   namespace App\Controller;

   class ArticlesController extends AppController{

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

       public function index(){

            // Set the view vars that have to be serialized.
            $this->set('articles', $this->paginate());
            // Specify which view vars JsonView should serialize.
            $this->set('_serialize', ['articles']);
       }
    }

Is there a way I can debug or pr the response and see how exactly the XML response will look like?


回答1:


in routes.php, insert

Router::extensions('xml');

just before

Router::defaultRouteClass('DashedRoute');

then, just use ".xml" in yout action:

/yourController/index.xml




回答2:


I am new in cakePhp, and using cackephp 3 (v 3.5). In my case just adding Router::extensions('xml');

to the routes.php didn't help. I have used more complex solution, but it works fine. In my SitemapController controller (/src/controller/SitemapController.php):

namespace App\Controller;

use Cake\Routing\Router;

class SitemapController extends AppController 
{
    public function initialize()
    {
        parent::initialize();

        // Set the response Content-Type to xml for each action
        $this->response->type(['xml' => 'application/xml']);       
        $this->response = $this->response->withType('xml');        
        // set layout 
        $this->viewBuilder()->setLayout('ajax');                
    } 

    /**
     * Shows index sitemap, which contains all the site's sitemaps (like pages)
     */
    public function index()
    {
        // ... some code here

        // just set the view vars to show in XML
        $this->set('baseUrl', Router::url('', true));
    }
// ... other code here
}

I have set response type as XML and set cacke's ajax layout - /src/Template/Layout/ajax.ctp (it only contains echo operator):

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

In my routes.php file

// sitemap index
Router::scope(
    '/sitemap.xml',
    ['controller' => 'Sitemap'],
    function ($routes) {
        $routes->connect(
            '/', 
            ['action' => 'index']
        );              
    }
);

Almost in the same way it works for json type of content.



来源:https://stackoverflow.com/questions/35102199/cakephp-3-creating-xml-view

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