Passing request data as XML in Laravel Http Client
Zubair Mohsin

Zubair Mohsin @zubairmohsin33

About: Full Stack Laravel Developer

Location:
Lahore, Pakistan
Joined:
Mar 4, 2019

Passing request data as XML in Laravel Http Client

Publish Date: Jun 3 '20
17 5

If you don't know about Laravel Http client yet, give it a read in the official documentation here.

Here's how you can pass the request data while making a POST, PUT or PATCH request as an array (transformed to JSON).

$response = Http::post('http://test.com/users', [
    'name' => 'Steve',
    'role' => 'Network Administrator',
]);
Enter fullscreen mode Exit fullscreen mode

What if you end up with an old school API that still uses XML to receive data?

Here's how you can do this:

    $response = Http::withHeaders([
        "Content-Type" => "text/xml;charset=utf-8"
    ])->send("POST", "http://some-url.com", [
        "body" => '<?xml version="1.0" encoding="utf-8"?>
                    <soap:Envelope
                    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                    xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
                        <soap:Body>
                            <SaveData xmlns="http://tempuri.org/">
                                <pParam>
                                    Value
                                </pParam>
                            </SaveData>
                        </soap:Body>
                    </soap:Envelope>'
    ]);
Enter fullscreen mode Exit fullscreen mode

If you know of a better alternative, please let me know :)

Comments 5 total

  • peter279k
    peter279kJun 3, 2020

    The PHP has the XML extension support.

    Try to look at the xmlwriter example :).

    • Zubair Mohsin
      Zubair Mohsin Jun 4, 2020

      Hi. Thanks for the reply.

      I am not sure how XMLWriter is relevant here?

      This is particularly about "sending xml as request data in an http request".

      • peter279k
        peter279kJun 4, 2020

        I think it can use the XML extension to generate XML dynamically.

        And not just use the XML string to be a request data.

  • Godluck Akyoo
    Godluck AkyooMar 4, 2021

    If you are using Laravel 7+ it is even easier

    Http::withHeaders(["Content-Type" => "text/xml;charset=utf-8"])
    ->post(self::CREATE_TOKEN_ENDPOINT, ['body' => $xml]);

Add comment