DEV Community 👩‍💻👨‍💻

Zubair Mohsin
Zubair Mohsin

Posted on

Passing request data as XML in Laravel Http Client

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('', [
    '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", "", [
        "body" => '<?xml version="1.0" encoding="utf-8"?>
                            <SaveData xmlns="">
Enter fullscreen mode Exit fullscreen mode

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

Top comments (5)

gpakyoo profile image
Godluck Akyoo

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]);

peter279k profile image

The PHP has the XML extension support.

Try to look at the xmlwriter example :).

zubairmohsin33 profile image
Zubair Mohsin Author

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 profile image

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

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

shadow243 profile image

🌚 Friends don't let friends browse without dark mode.

Sorry, it's true.