Building XML Web Services with PHP NuSOAP

 0  0  12  2019-03-16 06:54:22 Laporkan dokumen yang dilanggar

Building XML Web Services with PHP NuSOAP

  Aut hor: Ahm Asaduzzam an Dat e Added: 06t h Fed 2003 Type: Tut orial Rat ing: This is a print able version of " Building XML Web Services w it h PHP NuSOAP" . For t he com plet e online version, please visit ht t p: / / w w w .devart icles.com / cont ent .php?art icleI d= 414 Page 1: Introduction

I n t his art icle we will first t ry t o define Web Services, t heir advant ages and very basic archit ect ure.

  Then w e w ill w alk t hrough t w o exam ples, show ing how t o creat e Web Services w it h t he PHP NuSoap t oolkit and how t o invoke t hat service, which was developed in Visual Basic 6.0. I n t he second exam ple w e show how t o use Web Services w it h PHP. These exam ples dem onst rat e int eroperabilit y of Web Services ( plat form , operat ing syst em s and language independent ) .

Page 2: What are Web Services?

  

All fut ure soft ware applicat ions will be Web applicat ions, which will run over t he I nt ernet as services

for client s. Fut ure applicat ions w ill not cont ain large m asses of com piled execut able code ( EXE, DLL,

OCX, et c.) . Applicat ions will be broken down int o a num ber of sm aller individual services t hat are easier t o creat e and easier t o m aint ain. I ndividual services will be developed and m aint ained by sm aller groups of people. I t is t im e t o w ake up and get rid of our t radit ional skills. Find out how t o creat e fut ure I nt ernet applicat ions w it h t he t ools t hat are available t oday.

  So, what are Web Services? I f you ask t his quest ion t o five I T gurus, you m ay get six different

correct definit ions, however, a Web service is any piece of soft ware t hat m akes it self available over

t he I nt ernet and uses a st andardized XML m essaging syst em .

  XML lies in t he core of Web services, which was designed t o describe dat a. The m ain funct ions of

  

XML are int er - applicat ion com m unicat ion, dat a int egrat ion and ext ernal applicat ion com m unicat ion

w it h out side part ners. By st andardizing on XML, different applicat ions can m ore easily t alk t o one anot her, and t his m akes soft ware a whole lot m ore int erest ing. I f you want t o know about XML,

r ead t his XML t ut or ial, or if you want a m ore int uit ive feel for Web Services, t ry out t he I BM Web

Ser v ice Br ow ser , available on t he I BM Alphaworks sit e. The browser provides a series of Web Services dem onst rat ions. Find m ore resources her e.

  Benefit of Web Services Web Ser vices let applicat ions shar e dat a and—m ore powerfully —invoke capabilit ies from ot her

applicat ions wit hout regard t o how t hose applicat ions were built , what operat ing syst em or plat form t hey run on, and what devices are used t o access t hem . While XML Web Services rem ain

independent of each ot her, t hey can loosely link t hem selves int o a collaborat ing group t hat perform s

a part icular t ask. Read her e t o learn m ore about benefit s of different Web Services.

Evaluation of Web Services

  

Web Services didn't j ust exist suddenly. They aren't a new revolut ion; rat her t hey have t o be seen

as an evolut ion based on exist ing I nt ernet prot ocols. They are t he logical next st ep. Since 1994,

Dist ribut ed Obj ect s have been developed by several organizat ions under various nam es. NeXT called

t hem Port able Dist ribut ed Obj ect s, Microsoft called t hem Com ponent Obj ect Model ( COM) , I BM called t hem Syst em Obj ect Model ( SOM) , and Apple called t hem OpenDoc. These com panies ( w it h t he except ion of Microsoft ) form ed t he Obj ect Managem ent Group ( OMG) and converged upon a

st andard called Com m on Obj ect Request Broker Archit ect ure ( CORBA) . The concept was t o develop

an archit ect ure t hat let s applicat ions plug in t o an " applicat ion bus" and call a service. Based on

obj ect - orient ed unit s, it called on specialized soft ware com ponent s. Today, int eroperable obj ect s are

her e. being called Web Services. You can read a good int roduct ory art icle

Web Services Protocol Stack

  The Web Services prot ocol st ack consist s of t hree key XML- based t echnologies: SOAP ( Sim ple Obj ect Access Prot ocol) , WSDL ( Web Service Descript ion Language) , and UDDI ( Universal Descript ion, Discovery and I nt egrat ion) .

  

UD D I : This layer is responsible for cent ralizing services int o a com m on regist ry, and providing easy

publish/ find funct ionalit y. Current ly, service discovery is handled via t he UDDI . The UDDI specificat ion can help t o solve m aking it possible t o discover t he right services from t he m illions current ly online. Learn m ore about UDDI h er e.

  

W SDL: This layer is responsible for describing t he public int erface t o a specific Web service, which is

an XML- based language t hat describes t he various funct ions t hat a Web service is capable of.

  

Current ly, service descript ion is handled via t he WSDL. You do not need t o learn all t he nit t y - grit t y

det ails because t here are t ools t hat generat e WSDL for you. You can get one her e.

SOAP: This layer is responsible for encoding m essages in a com m on XML form at so t hat m essages

  can be underst ood at eit her end. Current ly, t his includes XML-RPC and SOAP. For exam ple, t he client program bundles up t wo values ( see Figure 1) t o be added int o a SOAP m essage, which is

sent t o t he Web service by sending it as t he body of an HTTP POST request . The server unpacks t he

  SOAP request t hat t he applicat ion can underst and and execut es Add operat ion. Next , t he server

packages up t hat result of sum m at ion as response int o anot her SOAP m essage, which it sends back

t o t he client program in response t o it s HTTP request . The client program unpacks t he SOAP m essage t o obt ain t he result s of t he sum m at ion. So, SOAP= XML + HTTP.

Figure 1

  

You can experim ent w it h Web Services using PHP by w rit ing only a few lines of code, w it hout having

t o set up a special environm ent . PHP is already broadly deployed for dat a - cent ric web applicat ions.

Your PHP- dr iven w eb sit es m ay have com ponent t hat m ay be r eused by exposing t heir m et hods

using SOAP or XML RPC and t his conversion process is t rivial using t he t ools available t oday. For t he

sake of sim plicit y w e w ill nar r ow dow n our discussion about SOAP. I n t he follow ing exam ple, w e w ill

NuSOAP, which is a com ponent - based Web Services t oolkit t hat allows user t o send and receive use

SOAP m essage over HTTP. Nu SOAP is dist ribut ed by NuSphere Corporat ion. I t is open source and

licensed under t he GNU LGPL.

Page 3: Walkthrough Example 1

  The inst allat ion of NuSOAP is a st raight forward process. Dow nload t he files and ext ract t he file

nusoap.php from t he zip. For easy access, copy t he classes t o a locat ion in your include pat h, or int o

t he direct ory ( say, ht t p: / / yourServer.com / nusoap/ ) in w hich you w ill be using t he classes. Let ’ s

develop a sim ple SOAP server wit h NuSOAP t oolkit t hat will provide updat e inform at ion ( whet her a

new updat e is released) of your soft w are product , w hich is inst alled in t he cust om er ’s com put ers.

  List in g: cvs.ph p Creat e a file ( in t his exam ple, cvs.php) and copy it t o locat ion ht t p: / / yourServer.com / nusoap/

  <?php require_once('nusoap.php'); // include the NuSOAP classes $s = new soap_server; // instantiate the server object, provided by soap_server classes $s -> register('cvs'); /* to allow our function to be called remotely, we must register it with the server object. If this is not done server will generate a fault indicating that the service is not available if a client accesses the service. In the absence of such a registration process, any PHP functions would be remotely available, which would present a serious security risk. */ function cvs ($StrBuild){ /* Now define our simple function that we are exposing as service. Notice that we first check to make sure a string (version info) was passed. If the parameter is not a string, we use the soap_fault class to return an error to the client. */ // Optionally catch an error and return a fault if($StrBuild == ''){ return new soap_fault('Client','','Must supply a valid build string.'); } if ($StrBuild < "200212") { // If customer is using an older version of the product return "A new version of this product is available now for download, please visit http://www.wordware.com/education"; } if ($StrBuild =="200212") { return "Update Not Necessary. Thank you for using our product."; } } $s -> service($HTTP_RAW_POST_DATA); /* The final step is to pass any incoming posted data to the SOAP server ’s service method. The method processes the incoming request and calls the appropriate function (in our case cvs ()). It will then formulate the response. */

  Now how your product w ill use t his service, w hich w ill aut om at ically not ify your cust om er if a new version of your applicat ion is available. For sim plicit y sake we will design t he following dialog wit h

  

VB. You can download t he proj ect file. You will find enough com m ent ary wit h code, which describes

how t o build SOAP envelope and parsing XML docum ent wit h Microsoft XML parser.

  Figure 2.1 Figure 2.2

Page 4: Walkthrough Example 2

  

Creat e a Web Service t hat will provide a list of all ATM m achines for a given zip code and develop a

web sit e wit h PHP t hat consum es t his service. Upon providing a ZI P code, user can get a list of ATM

services ( Figure 3) .

  Figure 3

  You can find a Web Service nam ed GeoCash , w hich pr ovide sim ilar ser vices. You m ay use t his her e. Let ’s walk ser vice for developm ent pur pose for 60 days w it h a t r ial key, for t r ial key check t hrough an exam ple, w hich consum es ( client .php) t his service.

  St ep 1 : Check WSDL file ( if any) for t his service. Prepare a request for t he service wit h ZI P code, i.e., m ake a SOAP envelope ( use PHP NuSOAP) St ep 2 : Get t he response ( XML docum ent ) and parse it w it h XML parser PHP EXPAT.

  St ep 3 : Display dat a ( Figure 3) List in g: Clie n t .ph p

  <html> <head> <title> AtM INFO</title> <body> <? $xml_file = ‘az.xml ’; require( ‘ nusoap.php ’); // Prepare SOAP envelop requesting the service $wsdlfile="http://ws2.serviceobjects.net/gc/GeoCash.asmx?WSDL"; $msg='<GetATMLocations ns="http://www.serviceobjects.com/"><PostalCode>20191</PostalCode> <LicenseKey>WS2 - BPN4- AFV4</LicenseKey></GetATMLocations>'; $s=new soapclient($wsdlfile,'wsdl'); // Invoking operation $s -> call('GetATMLocations',array($msg)); // Get the response $theXML= $s ->response; // To see the response, uncomment the following lines //echo ‘< xmp>’ .$ theXML.’ </ xmp>’ ; echo "<table border=5 cellpadding=5>"; echo "<tr><th colspan=2>ATM Info</th></tr>"; // write this response to a file for future pursing $fp = fopen ($xml_file, "w"); fwrite($fp, $theXML); fclose($fp); //Delete 1st 8 Lines which is not a part of XML file $filename = $xml_file; $fd = fopen ($filename, "r");

  $query_str="HTTP/1.1 200 OK"; $m_line=7;$tmp_line=0;$line=0; $m_filename = "result2.txt"; $m_fd = fopen($m_filename, "w"); while (!feof ($fd)) { $buffer = fgets($fd, 4096); $pos = strpos ($buffer, $query_str); if ($pos === false and $line==0) { fputs ($m_fd,$buffer); } else { if ($tmp_line < $m_line) { $tmp_line = $tmp_line + 1; $line = 1; } else { $line = 0; } } } fclose($fd); fclose($m_fd); copy("result2.txt","result.txt"); $xml_file=$m_filename; //create xml parser object $parser = xml_parser_create(); /* Define what to do when the parser encounters a start or end tag. Note that “ startElement” and “endElement ” are user - defined functions, which we will look at in a minute. You can name them whatever you want, but these names are the standard convention. */ xml_set_element_handler($parser,"startElement","endElement"); xml_set_character_data_handler ($parser, "characterData"); if (!($filehandler = fopen($xml_file, "r"))) { die("could not open XML input"); } /* We start reading the contents of the file, 4K at a time, and put it in the variable “$ data” until we reach the end of the file. We use xml_parse to parse each chunk as we go. */ while ($data = fread($filehandler, 4096)) { if (!xml_parse($parser, $data, feof($filehandler))) { die(sprintf("XML error:%s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } } fclose($filehandler); xml_parser_free($parser); echo "</table>";

  ?> </font> </body> </html> <?php // Functions // When the parser encounters the start element of a tag function startElement($parser_instance, $element_name, $attrs) { switch($element_name) { case "BANK" : echo "<tr><td><b><font face=verdana size=2 color=blue>"; break; case "ADDRESS" : echo "<b>"; break; case "LOCATION" : echo "<b>"; break; case "CITY" : echo "<b>"; break; case "STATE" : echo "<b>"; break; case "LATITUDE" : echo "<b>"; break; case "LONGITUDE" :echo "<b>"; break; case "NOTES" : echo "<b>"; break; } } // When the parser encounters the data within the start and end tag function characterData($parser_instance, $xml_data) { echo $xml_data; } // When the parser encounters the end element of a tag function endElement($parser_instance, $element_name) { switch($element_name) { case "BANK" : echo ", </font>"; break; case "ADDRESS" : echo ", </b>"; break; case "LOCATION" : echo ", </b>"; break; case "CITY" : echo ", </b>"; break; case "STATE" : echo " </b>"; break; case "LATITUDE" : echo ", </b>"; break; case "LONGITUDE" : echo ", </b>"; break;

case "NOTES" : echo " </b><tr><td><b>"; break; } } ?>

Page 5: Conclusion

  There you have it , Web Services in PHP. Now you can easily connect your applicat ions and share dat a bet ween t hem . Just im agine what 's possible! her e.

I f you have any quest ions or com m ent s about t his art icle please post t hem

  For m ore great program m ing art icles, please visit ht t p: / / w w w .devart icles.com . I f you have an

opinion or quest ion about t his art icle, t hen please post it at t he devArt icles developer forum , w hich

is locat ed at ht t p: / / w w w .devart icles.com / forum

Dokumen baru
Aktifitas terbaru
Penulis
123dok avatar

Berpartisipasi : 2019-03-13

Tags

Php Web Services With The Nusoap Library

Web Development Services Web Menggunakan Php

Bab 8 Web Services Jeni J2Me Bab08 Web Services

Oo Programming With Php Laporan Pemrograman Web Php Aplikasi Konversi Xml Database Skripsi Berbasis Web Opengis Web Services Architecture Description

Penerapan Xml Web Service Pada Sistem Di

05 Middleware Web Services Pdf

Building XML Web Services with PHP NuSOAP

Gratis

Feedback