2016-01-30 74 views
0

我需要將數組轉換爲XML響應。目標是在插件控制器中編寫一個函數並調用它,它將返回一個XML響應。CakePHP 3創建XML視圖

我一直在嘗試下面提到的CakePHP手冊中提到的代碼。

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']); 
     } 
    } 

有沒有一種方法可以調試或提示響應並查看XML響應的外觀如何?

在routes.php文件
+0

你需要注意技術術語,你指的是什麼「_response_」? HTTP響應或呈現的數據視圖內容? – ndm

+0

我的意思是HTTP響應。 –

+0

好的,爲什麼你需要在你的應用程序中做到這一點?你不能只使用你的瀏覽器網絡控制檯,並檢查實際收到的響應? – ndm

回答

2

,之前

Router::defaultRouteClass('DashedRoute'); 

插入

Router::extensions('xml'); 

然後,只需使用YOUT行動 「的.xml」:

/yourController/index.xml

0

我是cakePhp中的新人,並使用cackephp 3(v 3.5)。在我的情況下,只是加入 Router::extensions('xml');

到routes.php沒有幫助。 我已經使用了更復雜的解決方案,但它工作正常。 在我SitemapController控制器(/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 
} 

我已經設置響應類型爲XML,並設置cacke的Ajax佈局 - /src/Template/Layout/ajax.ctp(它只含有回聲運營商):

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

在我的routes.php文件文件

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

幾乎在它適用於JSON類型的內容的方式一樣。