In Magento 2 we can convert Shipping address or billing address into Html format using below code snippet. Sometimes we need to display entire shipping address into CSV column or any specific page at that time below html format will be useful.
You are familiar with How to Get Customer Default billing and shipping address You can also use shipping/billing address from above way.
For Example, We have just get order shipping address, First load order by order id and after getting order id we have fetch order shipping address.
Call below construct in your php file,
<?php
class MassExport {
public function __construct(
\Magento\Sales\Api\OrderRepositoryInterface $orderRepository,
\Magento\Customer\Model\Address\Config $addressConfig
) {
$this->orderRepository = $orderRepository;
$this->_addressConfig = $addressConfig;
}
/**
* Render an address as HTML and return the result
*
* @return string
*/
public function _getAddressHtml($orderId)
{
try {
$order = $this->orderRepository->get($orderId);
} catch (NoSuchEntityException $e) {
throw new \Magento\Framework\Exception\LocalizedException(__('This order no longer exists.'));
}
$address = $order->getShippingAddress();
$renderer = $this->_addressConfig->getFormatByCode('html')->getRenderer();
return $renderer->renderArray($address);
}
}
You need to get address renderer using \Magento\Customer\Model\Address\Config class.
pass html format code and you will get html formatted address.
Call from template file,
$orderId = 10;
$shippingAddress = $this->_getAddressHtml($orderId);
$shippingFormat = strip_tags($this->_getAddressHtml($shippingAddress));
echo $shippingFormat;
The result will be,
Veronica Costello
6146 Honey Bluff Parkway
Calder, Michigan, 49628-7978
United States
T:(555) 229-3326