Magento 2: Return JSON, XML, HTML & Raw Text Data Response from Controller

This article shows how you can return JSON data, XML data, HTML data, or Raw Text data from any Controller class in Magento 2.

Generally, in the Magento2 controller’s execute() function, we see the redirect or forwarding call which redirects to the specified URL page.

However, we might sometime need to return the JSON format data or even the raw text data.

Here, I will show how you can achieve this. I suppose the module name to be “Chapagain_HelloWorld“.
Return JSON data from Magento2 Controller

File: app/code/Chapagain/HelloWorld/Controller/Index/Index.php

resultPageFactory = $resultPageFactory;
$this->resultJsonFactory = $resultJsonFactory;
$this->urlModel = $urlFactory->create();

parent::__construct($context);
}
/**
* Example for returning JSON data
*
* @return string
*/
public function execute()
{
$result = $this->resultJsonFactory->create();

$data = [
‘foo’ =>’bar’,
‘success’ => true
];

$result->setData($data);

return $result;
}
}
?>

Output:

{“foo”:”bar”,”success”:true}
1

{“foo”:”bar”,”success”:true}

Return XML data from Magento2 Controller

File: app/code/Chapagain/HelloWorld/Controller/Index/Index.php

resultPageFactory = $resultPageFactory;
$this->resultRawFactory = $resultRawFactory;
$this->urlModel = $urlFactory->create();

parent::__construct($context);
}
/**
* Example for returning Raw Text data
*
* @return string
*/
public function execute()
{
$result = $this->resultRawFactory->create();

// Return XML data
$result->setHeader(‘Content-Type’, ‘text/xml’);
$result->setContents(‘
Mukesh Chapagain
Nepal
‘);

return $result;
}
}
?>

Output:

Mukesh Chapagain
Nepal

Return Raw Text or HTML data from Magento2 Controller

File: app/code/Chapagain/HelloWorld/Controller/Index/Index.php

resultPageFactory = $resultPageFactory;
$this->resultRawFactory = $resultRawFactory;
$this->urlModel = $urlFactory->create();

parent::__construct($context);
}
/**
* Example for returning Raw Text data
*
* @return string
*/
public function execute()
{
$result = $this->resultRawFactory->create();

// Return Raw Text or HTML data
// $result->setContents(‘Hello World’);
$result->setContents(‘Hello World‘);

return $result;
}
}
?>

Hope this helps. Thanks.

Leave a comment