Sunday, July 8, 2007

Sending XML files to a Webservice (Using cURL)

Calling Web Services. Great fun!! … when it works. One of the biggest challenges is to send the XML document and get the response back, an XML document in particular. I have come up with a PHP function that hides all the necessary logic from theuser and handles the posting of the XML document and returns whatever the server responds. It relies on PHP’s cURL library (so you need it properly configured on your server in order to work). All you need to do is create the XML document, choose the URL (and port) to which you want to post the XML document and the function takes care of the rest. Below is the function code. As you can see, the function can handle SSL-enabled servers, something that provides a great advantage, since many Web services run on HTTPS.

// open a http channel, transmit data and return received buffer
function xml_post($post_xml, $url, $port)
{
$user_agent = $_SERVER[’HTTP_USER_AGENT’];
$ch = curl_init(); // initialize curl handle
curl_setopt($ch, CURLOPT_URL, $url); // set url to post to
curl_setopt($ch, CURLOPT_FAILONERROR, 1); // Fail on errors
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // allow redirects
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); // return into a variable
curl_setopt($ch, CURLOPT_PORT, $port); //Set the port number
curl_setopt($ch, CURLOPT_TIMEOUT, 15); // times out after 15s
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_xml); // add POST fields
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
if($port==443)
{
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
}
$data = curl_exec($ch);
curl_close($ch);
return $data;
}

The example below shows how the function works, by posting a XML document of the form
<?xml version=”1.0″ encoding=”iso-8859-1″?>

<Document> 

  <Message> 

     Your Name  

  </Message>

</Document>
to a “listener” script, which takes the XML document and returns a reply (another XML document). In this case, the listener is very simple. All it does is replace the “Message” tag with “Reply” and print the resulting XML. Of course, the listener can do all sorts of things in response to the POST.

<?php 

   if ( !isset( $HTTP_RAW_POST_DATA ) )

   {

      $HTTP_RAW_POST_DATA = file_get_contents( ‘php://input’ ); 

   } 

   $xml = str_replace(”Message”,”Reply” , $HTTP_RAW_POST_DATA);  


   print((trim($xml)));

?>



You can download the function code, as well as a working example here. Let me know what you think.

No comments: