Receiving XML via POST in PHP.

In this tutorial, I will show you how to receive an XML string via raw post data using PHP. This can be accomplished by using the php://input IO stream.

Let’s take a look at the following PHP example:

In the code above:

  • We started off by validating the request method. If the request is not a POST request, our PHP script will send back a “405 Method Not Allowed” header to the client and then kill the script. This means that our script can not be accessed via GET, DELETE or HEAD, etc.
  • Using the php://input IO stream, we retrieved the raw post data. This stream allows us to read raw data from the request body.
  • We disabled the standard libxml errors by using the libxml_use_internal_errors function. As a result, we can control how XML validation errors are displayed. If you fail to do this, XML errors will be immediately outputted.
  • Using the simplexml_load_string function, we converted our XML string into a SimpleXMLElement object.
  • If we were unable to convert the string into an object, then it means that there were issues with the XML that we received. The function simplexml_load_string will return a boolean FALSE value if the string could not be converted. We handle such errors by sending a “400 Bad Request” to the client and by printing out the error messages.
  • Finally, we do a var_dump on the SimpleXMLElement object.

Hopefully, you found this guide helpful!

Facebook Comments