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.
1 2 3 4 5 6 7 8 9 10 11 |
$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!