xml - 如何在 Zend Framework 应用程序中返回 XML

标签 xml zend-framework response return

我在 ZF 应用程序中返回 XML 时遇到问题。 我的代码:

class ProjectsController extends Gid_Controller_Action
{
    public function xmlAction ()
    {
        $content = "<?xml version='1.0'><foo>bar</foo>";
        header('Content-Type: text/xml');
        echo $content;
    }
}

我还尝试了以下方法:

class ProjectsController extends Gid_Controller_Action
{
    public function xmlAction ()
    {
        $content = "<?xml version='1.0'><foo>bar</foo>";
        $this->getResponse()->clearHeaders();
        $this->getResponse()->setheader('Content-Type', 'text/xml');
        $this->getResponse()->setBody($content);
        $this->getResponse()->sendResponse();
    }
}

有人可以指出正确的方向如何实现这一目标吗?

最佳答案

更新

显然,Zend Framework 提供了一种开箱即用的更好方法。请检查ContextSwitch action helper文档。

您唯一可能想要更改的是在 Controller 的 init() 方法中强制使用 XML 上下文。

<?php

class ProjectsController extends Gid_Controller_Action
{
    public function init()
    {
        $contextSwitch = $this->_helper->getHelper('contextSwitch');
        $contextSwitch->addActionContext('xml', 'xml')->initContext('xml');
    }

    public function xmlAction()
    {
    }
}


旧答案。

它不起作用,因为 ZF 在您的代码之后同时呈现布局和模板。

我同意 Mark 的观点,应该禁用布局,但此外您还应该禁用 View 渲染器。当您要处理 XML 时,DOMDocument 肯定更可取。

这是一个示例 Controller ,它可以执行您想要的操作:

<?php

class ProjectsController extends Gid_Controller_Action
{
    public function xmlAction()
    {
        // XML-related routine
        $xml = new DOMDocument('1.0', 'utf-8');
        $xml->appendChild($xml->createElement('foo', 'bar'));
        $output = $xml->saveXML();

        // Both layout and view renderer should be disabled
        Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer')->setNoRender(true);
        Zend_Layout::getMvcInstance()->disableLayout();

        // Set up headers and body
        $this->_response->setHeader('Content-Type', 'text/xml; charset=utf-8')
            ->setBody($output);
    }
}

关于xml - 如何在 Zend Framework 应用程序中返回 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1542979/

相关文章:

http - Nodejs : apply headers and get response

java - 在 Jersey Response 中返回图像

xml - as3 xml 检查元素是否存在

java - Java 中对象 XML 序列化的最佳方法

javascript - 如何评估 fetch api 中收到的 http 响应

php - Zend Framework 和防止胖 Controller

来自 1 个按钮的 javascript 2 url

php - 如何使用 PHP CURL 强制 XML 响应

android - 如何使用 AppCompat v21 在 android 中创建 float 操作按钮 (FAB)?

php - PHP中的线程?