【问题标题】:How to return XML in a Zend Framework application如何在 Zend Framework 应用程序中返回 XML
【发布时间】:2009-10-09 10:18:38
【问题描述】:

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

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

【问题讨论】:

    标签: xml zend-framework response return


    【解决方案1】:

    更新

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

    您可能想要更改的唯一内容是在控制器的 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);
        }
    }
    

    【讨论】:

    • 在 zend 框架项目文件夹结构中,我应该在哪里放置这样的文件?不适合 MVC 存储桶范式
    • @b_dubb,您可以在视图模板中生成 XML,因此它几乎是 MVC。或者,您可以将部分代码包装在帮助程序中。
    • @b_dubb,也可以查看 ContextSwitch 动作助手:framework.zend.com/manual/en/…
    • 我更新了答案,ContextSwitch 动作助手是这样做的正确方法。
    【解决方案2】:

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

    <?xml version='1.0'>
    

    应该是

    <?xml version='1.0'?>
    

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

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

    您可能需要考虑contextSwitch action helper

    另外,您可能想要使用DomDocument 而不是直接输入 xml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-08
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多