How to Convert CURL XML Response into an Array in Magento 2

img How to Convert CURL XML Response into an Array in Magento 2

When it comes to secure and reliable to E-commerce platform that provides good customer experience along with lightning fast speed, Magento stands first. Every day a developer wakes up to create & develop something new to improve existing Magento E-commerce experience in such a way that can help store owners to increase revenue as well as enhance the customer shopping experience. By default, Magento 2 is very secure & handy with easy to use design interface that easily interact with various API and gateways to send & receive data. Recently we have been working on Magento based CURL project with one of the gateways in which we have to send data to the server and store received response into an object so we can easily use that response for the further development.

Also, meanwhile developing shipping & gateway extension, we came across the requirement where we need to get all the response data in an array and wanted to display it in such format.
So, here is how we have converted CURL XML response into an array in Magento 2 without any kind of hardcoding.

All you need to do is, just load up the XML in SimpleXML and use it directly as shown below.

 $ch = curl_init();
 $sendurl = "http://example.com";
 curl_setopt($ch, CURLOPT_URL, $sendurl);
 curl_setopt($ch, CURLOPT_POST, 1);
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
 $data = curl_exec($ch);
 curl_close($ch);
 $response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $data);
 $xml = new \SimpleXMLElement($data);
$array = json_decode(json_encode((array)$xml), TRUE);
print_r($array);

Now you know that how to store response, you can try it on different XML feeds from various APIs. Hit the stars below if it worked for you and comment down if you face any issue while implementing the code.
Happy Coding!

Previous Article

How to fix “Unique constraint violation found” in Magento 2 Checkout Page After Migration

Next Article

How to Add Date & Time Picker in Magento System Configuration

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨