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:

//Make sure that this is a POST request.
if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){
    //If it isn't, send back a 405 Method Not Allowed header.
    header($_SERVER["SERVER_PROTOCOL"]." 405 Method Not Allowed", true, 405);
    exit;
}


//Get the raw POST data from PHP's input stream.
//This raw data should contain XML.
$postData = trim(file_get_contents('php://input'));


//Use internal errors for better error handling.
libxml_use_internal_errors(true);


//Parse the POST data as XML.
$xml = simplexml_load_string($postData);


//If the XML could not be parsed properly.
if($xml === false) {
    //Send a 400 Bad Request error.
    header($_SERVER["SERVER_PROTOCOL"]." 400 Bad Request", true, 400);
    //Print out details about the error and kill the script.
    foreach(libxml_get_errors() as $xmlError) {
        echo $xmlError->message . "\n";
    }
    exit;
}


//var_dump the structure, which will be a SimpleXMLElement object.
var_dump($xml);

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!