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