user12783093
user12783093

Reputation:

Laravel Package for XML API Usage

Is there any laravel package for XML Api usage? I am developing one project using Laravel and I came to know that chase payment gateway doesn't get sdk for php. So is there any package to use XML api directly in laravel?

Upvotes: 1

Views: 1909

Answers (2)

Emanuel Bariki
Emanuel Bariki

Reputation: 11

In Laravel To send your payload as XML you can convert your PHP array to XML using the below code.

if (!function_exists('arrayToXml')) {
        # code...
        function arrayToXml($data, &$xmlData) {
            foreach($data as $key => $value) {
                if (is_array($value)) {
                    if (is_numeric($key)) {
                        $key = 'item' . $key; // Handling numeric keys
                    }
                    $subnode = $xmlData->addChild($key);
                    arrayToXml($value, $subnode);
                } else {
                    $xmlData->addChild("$key", htmlspecialchars("$value"));
                }
            }
        }
    }
    if (!function_exists('convertToXml')) {
        # code...
        function convertToXml($array, $root='root') {
            $xmlData = new SimpleXMLElement('<'.$root.'></'.$root.'>');
        
            arrayToXml($array, $xmlData);
    
            // Format (pretty-print) the XML
            $dom = new DOMDocument('1.0');
            $dom->preserveWhiteSpace = false;
            $dom->formatOutput = true;
            $dom->loadXML($xmlData->asXML());
            
            return str_replace('<?xml version="1.0"?>', "", $dom->saveXML());
        }
    }

You can send the returned array to your API.

To receive the response for this req. (Assuming the response will be in XML)

$response = xmlToArray($request->getContent());

The below function to convert the XML to a PHP Array.

if (!function_exists('xmlToArray')) {
    # code...
    function xmlToArray($xml) {
        $xmlObject = simplexml_load_string($xml, "SimpleXMLElement", LIBXML_NOCDATA);
        $json = json_encode($xmlObject);
        $array = json_decode($json, true);
        return $array;
    }
}

Upvotes: 0

Mark
Mark

Reputation: 1386

I wrote several helpful XML packages for Laravel.

Response XML: This one adds an xml method to the Response class.

E.g. return response()->xml(User::all());

Request XML: This one lets your api receive an incoming xml request and parse it so it can be run through Laravel's built in validation.

Collection XML: This one adds an xml method to Laravel's native Collection class.

Sounds like you may want to use this one if you're preparing data to send off to some other API that consumes XML. You can load your data into a collection and transform it into XML. E.g. $collection->toXml();

Upvotes: 1

Related Questions