How to consume a web service in PHP

Have you ever wondered how you can consume a web service in PHP? Although I code main in C#, I run quite a few sites in PHP and I wanted the ability to automatically notify ping servers when new content is available at my websites. This will bring the search engine crawlers almost immediately to my sites and get my content index faster. This is automatically done in WordPress by pinging PingOmatic but for sites which run my own Content Management System (CMS), I had to do the pinging myself.

You can easily do the pinging in PHP but I wanted the ability to send pings for scheduled content release. For if my content is going to be published on a date in the future, I need to be able to send the ping at that point in time. You can get a cron job to run a script for you or like WordPress does, hook a function to all HTTP requests to see if there are any pings to send. However I find the latter innappropriate and the former is just well PHP scripts and I’d rather have it done in C#.

My idea is to create a Web Service which will accept the title of the content, the URL where the content can be found and the publish date. This will then be saved in a table. A Windows Service will then check the table to see if any pings need to be sent. My Windows Service will run at say 30 mins, pretty much like a cron job.

Okay back to consuming web services in PHP, if you use the PHP function to do that, you will get some problems (I can’t recall exactly which one it was when I was googling). The best way is to use NUSOAP. You just need to download it from SourceForge and upload nusoap.php to your server. Once that is done, you can easily consume any web services as follows:


$client = new nusoap_client('http://www.mydomain.co.uk/Services/Ping.asmx?WSDL', 'wsdl');

$err = $client->getError();
if ($err) {
//echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
return $err;
}
// Doc/lit parameters get wrapped
$param = array('title' => $title, 'url' => $url, 'publishDate' => $publishDate);
$result = $client->call('Schedule', array('parameters' => $param), '', '', false, true);
// Check for a fault
if ($client->fault) {
//echo '<h2>Fault</h2><pre>';
//print_r($result);
//echo '</pre>';
return $result;
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
//echo '<h2>Error</h2><pre>' . $err . '</pre>';
return $err;
} else {
// Display the result
//echo '<h2>Result</h2><pre>';
//print_r($result);
//echo '</pre>';
return $result;
}
}

It is very straightforward to call a web service with nusoap and I recommend it. You can find more examples of how to call web services when you download the codes from Source Forge. The above did the trick for me.

comments powered by Disqus