13

我在 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();
    }
}

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

4

2 回答 2

25

更新

显然,Zend 框架为此提供了一种更好的方法。请务必检查ContextSwitch 操作帮助程序文档。

您可能想要更改的唯一一件事是在控制器的 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 的观点,布局应该被禁用,但除此之外你还应该禁用视图渲染器。当您要处理 XML 时,肯定 DOMDocument 更可取。

这是一个示例控制器,应该可以执行您想要的操作:

<?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);
    }
}
于 2009-10-09T17:11:52.327 回答
10

您缺少 xml 标记上的结尾问号:

<?xml version='1.0'>

它应该是

<?xml version='1.0'?>

此外,您可能需要禁用布局,以便仅打印 xml。将此行放在您的 xmlAction() 方法中

$this->_helper->layout->disableLayout();

您可能需要考虑contextSwitch 操作助手

此外,您可能希望使用DomDocument而不是直接输入 xml

于 2009-10-09T16:04:17.577 回答