So I need to build an application that will receive xml request and based on that I will have to return the response xml. I know how to send requests and receive the response, but I have never done it the other way. I would send the request like so:
private function sendRequest($requestXML)
{
$server = 'http://www.something.com/myapp';
$headers = array(
"Content-type: text/xml"
,"Content-length: ".strlen($requestXML)
,"Connection: close"
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $server);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $requestXML);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$data = curl_exec($ch);
if(curl_errno($ch)){
print curl_error($ch);
echo " something went wrong..... try later";
}else{
curl_close($ch);
}
return $data;
}
My question is - what would be the code on the receiving side? How do I catch the incoming request? Thanks.
To retrieve XML from the server, you need to send a GET request and specify the Accept: application/xml header in the request. The Accept header tells the server that your client is expecting XML data. Without this header, the server may return data in a different format.
$response = $client->get("computer/api/xml")->getBody(); Now we will parse XML data and convert it into JSON data using json_encode. For data processing, I have converted JSON into PHP array using json_decode method. $xml = simplexml_load_string($response); $json = json_encode($xml); $array = json_decode($json,TRUE);
Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML. HTML.
The general idea is to read in the POST value, parse it as XML, make a business decision on it, build out an XML response according to the API you've decided on, and write it into the response.
Read in the POST value:
$dataPOST = trim(file_get_contents('php://input'));
Parse as XML:
$xmlData = simplexml_load_string($dataPOST);
Then, you would build out an XML string (or document tree, if you wish), and print it out to the response. print() or echo() will do fine.
All you have to do on the receiving end is create a 'normal' PHP script. Depending on the protocol between your endpoint and the requesting service you need to grab the data from the correct location which is most likely going to be a $_GET or $_POST array.
You may have to read the raw POST data if it's not coming through in $_POST, take a peak at this article
http://www.codediesel.com/php/reading-raw-post-data-in-php/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With