Skip to content

Magento 2 : Controller Return XML or JSON

here’s example M2 controller serve XML or JSON

public function __construct(
\Magento\Framework\App\Action\Context $context,
\Magento\Framework\Controller\Result\RawFactory $resultPageFactory
) {
$this->resultPageFactory = $resultPageFactory;
parent::__construct($context);
}
public function execute()
{
$result = $this->resultPageFactory->create();
$xmlDummy = ‘<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>
<SomeXMLTag>
<MyTag>MyValue</MyTag>
</SomeXMLTag>

‘;

$result->setHeader(‘Content-Type’, ‘text/xml’);
$result->setContents($xmlDummy);
return $result;
}

for JSON you can use, but without setHeader

\Magento\Framework\Controller\Result\JsonFactory

Share

Comments are closed.