Consuming a WCF Service from PHP

This entry was posted by Solent Systems Webmaster on Wednesday, 5 May, 2010

Below is an example PHP script which accesses the sample WCF Service defined by the WCF template in Visual Studio 2010.

  1. GetDataUsingDataContract(CompositeType composite)

This function is declared by the template WCF Service in Visual Studio 2010.  It accepts a ‘CompositeType’ object as the parameter, which is itself defined within the webservice.  This object has two properties, a bool called ‘boolValue’, and a string called ‘stringValue’.

To pass a parameter from PHP, a similar class has to be defined within the PHP as well.

//Declare the class that will be passed as the parameter
  1. class myCompositeType{
  2.         public $boolValue;
  3.         public $stringValue;
  4. }
  5.  
  6. //instantiate an object of the class we just created
  7. $obj = new myCompositeType();
  8. //Assign values to the properties of the class
  9. $obj->boolValue=true;
  10. $obj->stringValue="World!";
  11.  
  12. //Wrap up the object before it can be passed
  13. //Ensure that the array key is exactly the same as the expected parameter name declared in the webservice.
  14. $myParameter = array('composite'=>$obj);
  15.  
  16. //Create a SOAP client
  17. $client = new SoapClient("path to your .wsdl");
  18.  
  19. //Call the method, passing our parameter
  20. $retVal = $client->GetDataUsingDataContract($myParameter);
  21.  
  22. //Handle the result, which is also an object of the myCompositeType class
  23. echo $retVal->GetDataUsingDataContractResult->stringVal;

(Ensure that the array key is exactly the same as the expected parameter name declared in the webservice.)


Leave a Reply