Magento 2 – How to Pass XML Data in Request Body for SOAP API Call

apimagento2soap-api

As I need to get the product data based on the SKU but need this in SOAP XML format.

I am creating the module for third-party integration which provides the SKU in soap XML formate based on that I need to return product data in XML format.

By default, Magento supports array, string, JSON in the request body. But we need to allow XML.

Best Answer

I have been there so i used this approach and this works for me

try to create XML in variable like this

foreach ($orderItems as $_item) {
            $orderItemstring = '<orderItem>
           <name>' . $_item->getName() . '</name>
           <barcode>' . $_item->getSku() . '</barcode>
           <externalId>' . $order->getIncrementId() . '</externalId>
           <quantity>' . (int) $_item->getQtyOrdered() . '</quantity>
           <costPerUnit>' . $_item->getPrice() . '</costPerUnit>
        </orderItem>';
        }

then final format of XML in another variable

$xmlSentToApi = '<?xml version="1.0" encoding="UTF-8"?>
                                        <apiRequest>
                                           <orders>' . $ordersstring . '</orders>
                                        </apiRequest>';

then send to API like this

$url = 'URL address';
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-Type: application/xml"));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $xmlSentToAPI);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

Hope this helps, upvote if it works for you