PHP: Send XML via POST.

This is a guide on how to send XML via a POST request using PHP. In this tutorial, I will be using the inbuilt cURL functions to send the request.

Let’s jump right in and take a look at the following code:

In the PHP above:

  1. We assigned our XML string to a PHP variable.
  2. We initiated cURL and specified the URL that we want to send our XML data to.
  3. Using the CURLOPT_HTTPHEADER option, we set the Content-Type header to text/xml. This may or may not be required depending on the service that you are sending your POST request to.
  4. In order to tell cURL that we want to send a POST request, we set the CURLOPT_POST option to TRUE. By default, cURL will send a GET request.
  5. We assigned our XML data to the body of the request.
  6. We told cURL to return the response output as a variable by setting the CURLOPT_RETURNTRANSFER option to TRUE.
  7. Finally, we executed the request and printed out the response. We also added in some basic error checking, just in case the request fails.

Send XML without cURL.

If you do not have access to the cURL functions, then you can check out my guide on sending a POST request without cURL.

Note that you may need to modify the function and change the header value on LINE 17. You may also need to remove the http_build_query function on LINE 11. This will all depend on the service you are sending your XML to.

Send XML file data via cURL.

If your XML content is located in a file, then you can read the contents of that file using the file_get_contents function:

In the example above, the file_get_contents function reads in XML data from a file called file.xml and assigns it to the variable $xml. This code would replace the XML assignment on LINE 2 of the original example above.

Hopefully, you found this post to be helpful!

Related article: Receive XML via POST.

Facebook Comments