How to easily consume a web service from PHP - php

Is there available any tool for PHP which can be used to generate code for consuming a web service based on its WSDL? Something comparable to clicking "Add Web Reference" in Visual Studio or the Eclipse plugin which does the same thing for Java.

In PHP 5 you can use SoapClient on the WSDL to call the web service functions. For example:
$client = new SoapClient("some.wsdl");
and $client is now an object which has class methods as defined in some.wsdl. So if there was a method called getTime in the WSDL then you would just call:
$result = $client->getTime();
And the result of that would (obviously) be in the $result variable. You can use the __getFunctions method to return a list of all the available methods.

I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.

I have used NuSOAP in the past. I liked it because it is just a set of PHP files that you can include. There is nothing to install on the web server and no config options to change. It has WSDL support as well which is a bonus.

This article explains how you can use PHP SoapClient to call a api web service.

Say you were provided the following:
<x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:int="http://thesite.com/">
<x:Header/>
<x:Body>
<int:authenticateLogin>
<int:LoginId>12345</int:LoginId>
</int:authenticateLogin>
</x:Body>
</x:Envelope>
and
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<authenticateLoginResponse xmlns="http://thesite.com/">
<authenticateLoginResult>
<RequestStatus>true</RequestStatus>
<UserName>003p0000006XKX3AAO</UserName>
<BearerToken>Abcdef1234567890</BearerToken>
</authenticateLoginResult>
</authenticateLoginResponse>
</s:Body>
</s:Envelope>
Let's say that accessing http://thesite.com/ said that the WSDL address is:
http://thesite.com/PortalIntegratorService.svc?wsdl
$client = new SoapClient('http://thesite.com/PortalIntegratorService.svc?wsdl');
$result = $client->authenticateLogin(array('LoginId' => 12345));
if (!empty($result->authenticateLoginResult->RequestStatus)
&& !empty($result->authenticateLoginResult->UserName)) {
echo 'The username is: '.$result->authenticateLoginResult->UserName;
}
As you can see, the items specified in the XML are used in the PHP code though the LoginId value can be changed.

Well, those features are specific to a tool that you are using for development in those languages.
You wouldn't have those tools if (for example) you were using notepad to write code. So, maybe you should ask the question for the tool you are using.
For PHP: http://webservices.xml.com/pub/a/ws/2004/03/24/phpws.html

HI I got this from this site : http://forums.asp.net/t/887892.aspx?Consume+an+ASP+NET+Web+Service+with+PHP
The web service has method Add which takes two params:
<?php
$client = new SoapClient("http://localhost/csharp/web_service.asmx?wsdl");
print_r( $client->Add(array("a" => "5", "b" =>"2")));
?>

Related

Generating a client with Soap 1.2 in php

Could you tell me if there is a tool to generate a soap client with these requirements:
soap 1.2
the client is based on three different service (so 3 wsdl)
those services have shared types
I found out about:
http://php.net/manual/en/class.soapclient.php
and
http://www.php.net/manual/en/soapclient.soapclient.php
The thing I can't find out searching for it is especially the last two point.
Any help will be appreciated because I can't unserstand how to create it from different sources and how to call a specific service.
I can't test my solution as i don't have 2-3 web services running, but i think this solution will work (if i understood you correctly). Please if you can try it and let me know.
<?php
class wstest {
function __construct($url) {
$this->soapUrl = $url;
try{
$this->client = new SoapClient($this->soapUrl,array('login' => 'wsuser', 'password' => "some_password", "connection_timeout"=>30,'trace'=>true,'keep_alive'=>false,'features' => SOAP_SINGLE_ELEMENT_ARRAYS));
} catch (Exception $e) {
echo $e->getMessage();
}
}
};
$con = new wstest("http://firstwebservice.com/?wsdl");
$con2 = new wstest("http://secondwebservice.com/?wsdl");
$con3 = new wstest("http://thirdwebservice.com/?wsdl");
?>
I'm trying to figure out what you might want to do.
First: One WSDL === one Service === one SoapClient. You cannot mix two WSDL locations on the Soap client level, but depending on your application, might connect each services' results on a higher level.
So if you have three WSDL, then you must instantiate three SoapClient classes to be used. It's not like a single generic HTTP Client which can make requests to any existing webserver.
Second: Unless you provide a classmap to the SoapClient, the return value of any request is only a mixture of stdClass and array. There might be types defined in the WSDL, but PHP does not map them to anything unless you define it.
I would recommend using a classmap with your own defined classes that match the ComplexType definitions in the WSDL. There are some code generators to be googled that might do the job, but the Soap standard is complex, as is the definitionof WSDL, so you might end up doing work by hand.
You can perfectly live without a classmap if the data structures are small.
Third: If the three WSDL share data types, this will not affect PHP in any way. Since without classmap the responses are stdClass and Array, and the Request parameters can be the same, you won't get any benefit from this information.
If on the other hand you go the way of the classmap, I'd expect that the shared types will lead to the same classes generated, so you would also see on the PHP level that a ComplexType from Service A is identical to the ComplexType of Service B.

How to generate wsdl

I am working for the first time on SOAP. After going through various tutorials I have been able to create a small and simple soap server which offers two functions. Although I have been able to create the SOAP service and test it with a client I am not being able to understand WSDL even after going through the tutorials e.g. at http://www.w3schools.com/wsdl/wsdl_binding.asp .
So how can I make this SOAP "wsdl soap" ?? Is there anyway way to autogenerate it in PHP? I don't mind writting it down manually provided I know what to write. Where do I put what code to make it "wsdl" ??
function geolocate(double $lat, double $lng)
{
$contents = file_get_contents('http://api.geonames.org/findNearby?lat='.$lat.'&lng='.$lng.'&username=imranomar');
return $contents;
}
function describe(long $geonameid)
{
return file_get_contents('http://ws.geonames.org/get?geonameId='.$geonameid.'&style=full');
}
$server = new SoapServer(null, array('uri' => "urn://localhost/firstmobile?wsdl"));
$server->addFunction('geolocate');
$server->addFunction('describe');
$server->handle();
Note: I cannot be using any framwork
I suggest you use Zend_Soap_Server as it simplify webservices developpement in PHP.
It is possible to auto generate SOAP WSDL using Zend AutoDiscovery

Creating a web service in PHP

I would like to create a web service in PHP which can be consumed by different consumers (Web page, Android device, iOS device).
I come from a Microsoft background so am confortable in how I would do it in C# etc. Ideally I would like to be able to provide a REST service which can send JSON.
Can you let me know how I can achieve this in PHP?
Thanks
Tariq
I developed a class that is the PHP native SoapServer class' REST equivalent.
You just include the RestServer.php file and then use it as follows.
class Hello
{
public static function sayHello($name)
{
return "Hello, " . $name;
}
}
$rest = new RestServer(Hello);
$rest->handle();
Then you can make calls from another language like this:
http://myserver.com/path/to/api?method=sayHello&name=World
(Note that it doesn't matter what order the params are provided in the query string. Also, the param key names as well as the method name are case-insensitive.)
Get it here.
I would suggest you go for Yii it is worth of learning. You can easily establish it in this.
Web Service. Yii provides CWebService and CWebServiceAction to simplify the work of implementing Web service in a Web application. Web service relies on SOAP as its foundation layer of the communication protocol stack.
Easiest way in PHP is to use GET/POST as data-in and echo as data-out.
Here's a sample:
<?php if(empty($_GET['method'])) die('no method specified');
switch($_GET['method']){
case 'add': {
if(empty($_GET['a']) || empty($_GET['b'])) die("Please provide two numbers. ");
if(!is_numeric($_GET['a']) || !is_numeric($_GET['b'])) die("Those aren't numbers, please provide numbers. ");
die(''.($_GET['a']+$_GET['b']));
break;
}
}
Save this as test.php and go to http://localhost/test.php?method=add&a=2&b=3 (or wherever your webserver is) and it should say 5.
PHP does have native support for a SOAP server ( The SoapServer class manual shows it) and I've found it pretty simple to use.
Creating a REST style API is pretty easy if you use a framework. I don't want to get into a debate about which framework is better but CakePHP also supports output as XML and I'm pretty sure others will as well.
If you're coming from a Microsoft background just be careful about thinking about "datasets". They are a very specific Microsoft thing and have been a curse of mine in the past. It's probably not going to be an issue for you, but you may want to just see the differences between Microsoft and open implementations.
And of course PHP has a native json_encode() function.
You can check out this nice RESTful server written for Codeigniter, RESTful server.
It does support XML, JSON, etc. responses, so I think this is your library.
There is even a nice tutorial for this on the Tutsplus network -
Working with RESTful Services in CodeIgniter
You can also try PHP REST Data Services https://github.com/chaturadilan/PHP-Data-Services
You can use any existing PHP framework like CodeIgniter or Symfony or CakePHP to build the webservices.
You can also use plain PHP like disscussed in this example

using functions from internal SOAP interface via php

I received a manual to internal SOAP interface of my partner. It says:
MyPARTNER web services are provided in the form of a SOAP interface. The service is available in this URL: https://justsomeurl.com:435/soap
then some bla bla about authorization etc. and then a part about Accessible Methods:
pull()
The PULL method is used for pulling data from the database. The method
receives a unique data based parameter under an internal name
requestXML. This parameter contains data in a structured XML format.
String pull(String requestXML)
The XML contains data required to make the request, and the response
data is sent back.
then some other methods, error codes, it's not important here...
The problem is that I'm totally unexperienced in SOAP so I don't know how to use this interface via PHP. I've tried to find some examples, tutorials and I am now little bit more informed about SOAP and its functionality but still haven't found any advice about how to use interface like this...
thanx for any help
Php comes with PHP SOAP libraries, that usually are included and enabled after a common php installation.
Yuo are asked to biuld the client part of the webservice pattern. Your partner should provide you the .wsdl of the web service. The wsdl describes the avialble method, the parameters they need and what they return.
Tipically parameters and return values are array structures
This could be a skeleton for your code:
//build a client for the service
$client = new SoapClient("partner.wsdl");
//$client is now a sort of object where you can call functions
//prepare the xml parameter
$requestXML = array("parameter" => "<xml>Hello</xml>");
//call the pull function this is like
$result = $client->__soapCall("pull", $requestXML );
//print the value returned by the web service
print_r($result);
Here follows a non-wsdl example
First the location paramater is the address the SOAP request will be sent to.
The uri parameter is the target namespace of the SOAP service. This is related to xml namespaces.
A sample code for you could be:
//for URI specification you should watch your partners documentation. maybe also a fake uri (like mine) could work
//build a client for the service
$client = new SoapClient(null, array(
'location' =>
"https://justsomeurl.com:435/soap",
'uri' => "urn:WebServices",
'trace' => 1 ));
// Once built a non-wsdl web service works as a wsdl one
//$client is now a sort of object where you can call functions
//prepare the xml parameter
$requestXML = array("parameter" => "<xml>Hello</xml>");
//call the pull function this is like
$result = $client->__soapCall("pull", $requestXML );
//print the value returned by the web service
print_r($result);
Here a useful link: http://www.herongyang.com/PHP/SOAP-Use-SOAP-Extension-in-non-WSDL-Mode.html

Generating WSDL when using PHP's native SOAP class?

I'm using the native SOAP class in PHP 5, having changed from NuSOAP as the native class is faster (and NuSOAP development seems to have ceased). However the PHP 5 SOAP lacks the ability to generate WSDL.
Has anyone experience of generating WSDL in PHP? If so, please recommend your preferred method.
Thanks.
Stuart,
If you or anyone else is looking for a solution to this problem here's what I did.
First get this script: http://www.phpclasses.org/browse/download/zip/package/3509/name/php2wsdl-2009-05-15.zip
Then look at its example files. After that I just sliced it the way I needed because I'm using codeigniter:
function wsdl(){
error_reporting(0);
require_once(APPPATH."/libraries/WSDLCreator.php"); //Path to the library
$test = new WSDLCreator("Webservice", $this->site."/wsdl");
//$test->includeMethodsDocumentation(false);
$test->addFile(APPPATH."/controllers/gds.php");
$test->addURLToClass("GDS", $this->site);
$test->ignoreMethod(array("GDS"=>"GDS"));
$test->ignoreMethod(array("GDS"=>"accessCheck"));
$test->createWSDL();
$test->printWSDL(true); // print with headers
}
That it, your all done.
Btw, I'm using SoapServer and SoapClient in php5+
You can try these options:
- https://code.google.com/p/php-wsdl-creator/ (GPLv3)
- https://github.com/piotrooo/wsdl-creator/ (GPLv3)
- http://www.phpclasses.org/package/3509-PHP-Generate-WSDL-from-PHP-classes-code.html (BSD like)
The first one might be your best option if the licence fits your project.
Generating a WSDL on the fly is not something that happens very often - it would tend to raise a few questions about the stability of your service!
Zend Studio can generate a WSDL from a PHP class, and there are a few other similar tools.
If you do need to generate the WSDL dynamically, take a look at Zend Framework library: Zend_Soap_AutoDiscover
Zend_Soap_AutoDiscover is a good alternative to NuSOAP. But, you can also create the WSDL file from scratch which can be very complicated and error prone. To ease this process, you can use an IDE to generate the WSDL file for your PHP functions and pass it as a parameter to your PHP SoapServer class. Check out the complete tutorial on How to generate wsdl for php native soap class

Categories