Using SOAP in PHP

Using SOAP in PHPThis document assumes knowledge of PHP and that you know what SOAP is. If you do not know what SOAP is, see my paper 'what is soap?' here.

PHP is so popular across the internet; most hosting companies and campuses have it installed; that quite often we are asked how to use PHP to deploy or access webservices using XML-RPC/SOAP. Although PHP is not my choice for doing webservices I can and will answer this question, with just one word of caution: PHP handles data types really poorly, don't use it for any complex services.

Which Library To Use

First thing no one has a desire to manually parse XML, build envelopes and do networking (if you do quit reading now and see: www.w3c.org for the specs). So we should choose a library (or class) to do the tedious work for us. There are many to pick from, just take a look on google, but I think the best is dietrich's 'NUSOAP' which can be downloaded free from http://dietrich.ganx4.com/nusoap/index.php. Download it and install it somewhere the webserver has access to.

Building a (very) Basic Service

You'll now want to do a basic service (server). The following code is a variation on the required hello world example. It will return a greeting when called upon by a client. The variation is that it requires a name to send a greeting to.

<?php
require_once('nusoap.php');
$s = new soap_server;
$s->register('helloyou');

function helloyou($name){
// We require the name of the person we are saying hello to
// so if they do not supply it we return an fault message.
if($name == ''){
return new soap_fault('Client','','I do not know who you are!');
}
return "hello $name!";
}
$s->service($HTTP_RAW_POST_DATA);
?>

Building a (very) Basic Client

Now that you have a basic server script written, place it on your webserver. Now we can write a client to access it. The following is super basic! A user fills in a form with their name and then the webservice is accessed to get a greeting for the user.

<?php include('/path/to/nusoap.php'); ?>
<html>
<!--Yes I am aware I am missing the DOCTYPE tag.-- >
<body>
<from id="Some form" action="THISDOCNAME.php" method="get">
Name:<input name="name" type="text" value="world">
<input type="submit" value="submit">
</form>
<?php
if ($name) {
require_once('nusoap.php');
//we create an array with the element name that has the form value of name
$parameters = array('name'=>$name);

//now we must create a soapclient object
$soapclient = new soapclient('http://x2studios.com/helloyou.php');
//now we call the server.
echo "Greeting returned", $soapclient->call('helloyou',$parameters);
}
?>
</body>
</html>

Handling Errors and Debugging

Services like the one above, as simple as they are, may still require error handling. For example if the client submitted the name as NULL the server would return an error message. To see what I mean take the 'if ($name)' out of the client example and then add the following error handling code to see for yourself:


$soapclient = new soapclient('http://x2studios.com/papers/examples/4/helloyou.php');
//now we call the server.
$result = $soapclient->call('helloyou',$parameters);
if ($err = $soapclient->getError()) { // if error returned then this has a value
echo 'The Server returned error: ', $err; // echo the error faultstring
} else {
echo 'Greeting returned: ', $result;
}

Something a Little More Useful

So it's all well and good to do simple scripts. But, now you want to venture in to doing some more complex?

The following will demonstrate a webservice to list courses available to students from a db over a network. The client will connect to the webservice and request a course listing. The courses will be pulled from a MySQL database and the results returned as a nested array to the client.

The DB

# This is the SQL to create the table
# in MySQL.
#
# Table structure for table `courses`
#

CREATE TABLE courses (
id int(11) NOT NULL auto_increment,
name text NOT NULL,
number int(11) NOT NULL default '0',
seats int(11) NOT NULL default '0',
PRIMARY KEY (id)
) TYPE=MyISAM;

#
# data for table `courses`
#

INSERT INTO courses VALUES (1, 'ENGR', 1215, 15);
INSERT INTO courses VALUES (2, 'ENGR', 1233, 20);
INSERT INTO courses VALUES (3, 'MATH', 1219, 32);
INSERT INTO courses VALUES (4, 'ENGL', 1209, 17);
INSERT INTO courses VALUES (5, 'PHYS', 1205, 30);
INSERT INTO courses VALUES (6, 'ARCH', 3305, 12);
INSERT INTO courses VALUES (7, 'ARCH', 1201, 16);

The Server

<?php

require_once('nusoap.php');
$s = new soap_server;
$s->register('getcourses');

function getcourses(){
$course = new EXAMPLE;
return $course->ListCourses();
}
$s->service($HTTP_RAW_POST_DATA);

class EXAMPLE {

function DB_Open(){
mysql_connect ("localhost", "login", "password");
mysql_select_db ("soapexamples");
}

function ListCourses(){
$this->DB_Open();
$query = "SELECT * FROM courses ORDER BY name, number ASC;";
$result = mysql_query($query);
$cnt = 0;
while ($course = mysql_fetch_assoc($result)){
$courses[$cnt] = array('name' => $course["name"], 'number' => $course["number"], 'seats' => $course["seats"]);
$cnt = $cnt + 1;
}
return $courses;
}
}
?>

The Client

This is not the most complex thing ever, but it does give you a 'real life' type example. The client doesn't send anything and I have no security implementation here… Check the papers at http://www.x2studios.com for a paper on SOAP security (I am writing that next).

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"
"http://www.w3.org/MarkUp/Wilbur/HTML32.dtd">
<html>
<body>
<?php
require_once('nusoap.php');
$soapclient = new soapclient('http://x2studios.com/papers/examples/4/course_server.php');
// $soapclient->debug_flag=true; //turn on debugging
$courses = $soapclient->call('getcourses');
// echo $soapclient->request; // shows XML of SOAP request
// echo $soapclient->response; //shows XML of SOAP response

foreach ($courses as $c) {
// The array is nested so this has the same recursions as there are courses
foreach ($c as $info) {
// this only loops once, but you need it anyway. (the array is 3d even
// though there are only 2d of intended structure)
echo "Name: ";
echo $info["name"];
echo " Number: ";
echo $info["number"];
echo " Seats: ";
echo $info["seats"];
}
echo "<hr />";
}
?>
</body>
</html>

Other Things

  • NuSOAP also allows the use of WSDL pages to access webservices, you'll want to look at the 'READ ME' file that comes with the download. I will not cover it here, because, it works basically the same way as above.
  • I've put the example files online at: www.x2studios.com
  • The server components are online as addressed in the example files.
  • The Client php's are online here and here .

Have fun!


Related Articles

  • Using SOAP in PHP
    Implementing webservice servers and clients using SOAP and PHP. This paper has examples and explanations regarding implimenting effective webservices.
  • An Extensive Examination of Web Services: WSE standards
    As weve discussed in the previous installments of this article series, Web services are comprised of a number of core standards, including: XML, SOAP, WSDL
  • Spell Checker with the Google Web API
    This article is a tutorial on how to use Google Web API to creat your own Spell Checker. Although the article is short it is very helpful. It provides the necessary coding and screenshots that make it easy to follow the authors direc.....
  • Web Services Interoperability
    Interoperability is one of the main promises of Web services. Web services are designed to be independent of the underlying operating system and programming language.
    In this article we will address some basic web services interoperability issues that are useful for developers. We will focus on...
  • Blog Traffic - Also Call Site Traffic
    Everybody is doing blogging these days but if you really want to stand out you have got to find ways to attract people to your blog site. Click here to find out the best ways to accomplish such a task.
  • Take The Logo Litmus Test
    Here is your C.I.T.T. (pronounced kit) [Color
  • Web Service Messaging
    Web services are revolutionizing the Internet by enabling applications to speak a common language: XML. While Web services technology enables the execution of remote functions, it does not provide a robust infrastructure for handling information.
  • Design Vs Content: Who Is King?
    am a firm advocate of good design but most of the time people tend to interpret design as amazing graphics and astounding visuals they tend to forget that design is the culmination of every aspect of good and effective presentation into one (visit Vincent Flanders WebPagesThatSuck.com). We all....
  • The Importance of Color in Web Designing
    A website is basically a marketing tool, representing the companies, products and services it is also a reflection of the companies personality, ideologies and philosophies. It is definitely a heavy burden to carry for a mere website, but it dose. Huge corporations spend millions of dollars to deter...
  • The Importance of Color in Web Designing
    This is must read info for any body in the visual arts - digital included. The author explains color theory as it relates to webpage design. Each section has good examples you can follow.

Contact Web Design Outsource and get started today

Need Website Designing, Development, Redesigning, Maintenance and SEO services or help growing your company's web presence? Request a free Quote Now.