How to return XML in a Zend Framework application

后端 未结 2 1486
旧巷少年郎
旧巷少年郎 2020-12-31 08:35

I\'m having problems returning XML in my ZF application. My code:

class ProjectsController extends Gid_Controller_Action
{
    public function xmlAction ()
          


        
2条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 09:22

    UPDATE

    Apparently, Zend Framework provides a way better method for that out of the box. Please do check the ContextSwitch action helper documentation.

    The only thing you might want to change is force XML context in controller's init() method.

    _helper->getHelper('contextSwitch');
            $contextSwitch->addActionContext('xml', 'xml')->initContext('xml');
        }
    
        public function xmlAction()
        {
        }
    }
    


    Old answer.

    It doesn't work because ZF renders both layout and template after your code.

    I agree with Mark, layout should be disabled, though in addition you should also disable view renderer. And definitely DOMDocument is much more preferable when you're going to deal with XML.

    Here is a sample controller that should do what you want:

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

提交回复
热议问题