【问题标题】:sending xml response from cakephp从 cakephp 发送 xml 响应
【发布时间】:2013-10-23 10:12:40
【问题描述】:

我想从我的 cakephp 控制器操作发送一个 xml 响应。我一直在尝试遵循官方指南:http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

但我不断收到此错误:

Missing View

Error: The view for ServicesController::index() was not found.

这是我的服务控制器的样子:

<?php
class ServicesController extends AppController {

    var $uses = array();
    var $components = array('Auth','Session','RequestHandler');

    function beforeFilter() {
        $this->Auth->allow('index');
    }

    function index(){
        $output = array(
            "status" => "OK",
            "message" => "You are good"
        );

        $this->set('output', $output );
        $this->set('_serialize', array("output"));
   }
}
?>

我还在我的routes.php 中添加了以下行

Router::parseExtensions('json', 'xml');

我做错了什么??

【问题讨论】:

  • 我最初回答说你只需要创建一个视图文件,但似乎我错了——至少根据书,你不应该需要一个。
  • 没错!我发现还有一个链接也是同样的:yihangho.com/cakephp-json-and-xml-response-explained
  • 您是否忘记将 .xml 扩展名添加到您的 url (example.com/services/index.xml)?
  • @AndrewBashtannik 你打败了我。这很可能是这里的答案。仅当您实际使用扩展时,使用 parseExtensions 才有意义。
  • 是的,我将扩展名添加到 url。尝试了json和xml。甚至尝试使用 CURL 进行测试

标签: php xml cakephp


【解决方案1】:

您可以尝试将您的数组转换为 XML,回显输出并退出函数:

function index(){
    $output = array(
        "root" => array( // It needs one top element (http://book.cakephp.org/2.0/en/core-utility-libraries/xml.html#transforming-an-array-into-a-string-of-xml)
            "status" => "OK",
            "message" => "You are good"
        )
    );

    $xmlObject = Xml::fromArray($output);
    echo $xmlObject->asXML();
    exit;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-08
    • 2016-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-12
    • 2011-02-26
    相关资源
    最近更新 更多