How to read soap response xml in php - php

This is my Soap Response xml,I need to get RebillCustomerID
How I can do this?
<?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Header><eWAYHeader
xmlns="http://www.eway.com.au/gateway/rebill/manageRebill">
<eWAYCustomerID>87654321</eWAYCustomerID><Username>test#eway.com.au</Username>
<Password>test123</Password></eWAYHeader></soap:Header><soap:Body>
<CreateRebillCustomerResponse xmlns="http://www.eway.com.au/gateway/rebill/manageRebill"><CreateRebillCustomerResult>
<Result>Success</Result><ErrorSeverity /><ErrorDetails />
<RebillCustomerID>90246</RebillCustomerID></CreateRebillCustomerResult>
</CreateRebillCustomerResponse></soap:Body></soap:Envelope><pre></pre>

try the code below. I am assuming your xml response is in $soapXMLResult variable
$soap = simplexml_load_string($soapXMLResult);
$response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children()->CreateRebillCustomerResponse;
$customerId = (string) $response->CreateRebillCustomerResult->RebillCustomerID;
echo $customerId;

How I did, create eway soap request and get eway soap result,may help others!
<?php
$URL = "https://www.eway.com.au/gateway/rebill/test/manageRebill_test.asmx?wsdl";
$option = array("trace"=>true);
$client = new SOAPClient($URL, $option);
$functions = $client->__getFunctions();
$headeroptions=array('eWAYCustomerID'=>"87654321",'Username'=>"test#eway.com.au","Password"=>"test123");
$header = new SOAPHeader('http://www.eway.com.au/gateway/rebill/manageRebill', 'eWAYHeader',$headeroptions);
$bodyoptions = array(
"CreateRebillCustomer" => array(
"customerTitle" => "Mr",
"customerFirstName"=>"Muhammad",
"customerLastName"=>"Shahzad",
"customerAddress"=>"cust ome rAddress",
"customerSuburb"=>"customer Suburb",
"customerState"=>"ACT",
"customerCompany"=>"customer Company",
"customerPostCode"=>"2345",
"customerCountry"=>">Australia",
"customerEmail"=>"test#gamil.com",
"customerFax"=>"0298989898",
"customerPhone1"=>"0297979797",
"customerPhone2"=>"0297979797",
"customerRef"=>"Ref123",
"customerJobDesc"=>"customerJobDesc",
"customerComments"=>"customerComments",
"customerURL" => "http://www.acme.com.au"
)
);
try{
$response = $client->__soapCall("CreateRebillCustomer", $bodyoptions,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//$response = $client->CreateRebillCustomer($bodyoptions);
//echo "<pre>";echo "<br/>";
// print_r($response);
echo $result = $response->CreateRebillCustomerResult->Result;echo "<br/>";
echo $customerId = $response->CreateRebillCustomerResult->RebillCustomerID;echo "<br/>";
echo "<br/>";
if($result=='Success' AND $customerId){
echo 'Member Created at eWay Successfully!...<br/>';
echo 'Creating Recurring Billing Cycle on eWay,Please wait......<br/>';
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillCustomerResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillCustomerResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
if($customerId){
$bodyoptions2 = array(
"CreateRebillEvent " => array(
"RebillCustomerID" => $customerId,
"RebillInvRef" => "Ref123",
"RebillInvDes"=>"description",
"RebillCCName"=>"Mr Andy Person",
"RebillCCNumber"=>"4444333322221111",
"RebillCCExpMonth"=>"12",
"RebillCCExpYear"=>"15",
"RebillInitAmt"=>"100",
"RebillInitDate"=>date('d/m/Y'),
"RebillRecurAmt"=>"200",
"RebillStartDate"=>date('d/m/Y'),
"RebillInterval"=>"31",
"RebillIntervalType"=>"1",
"RebillEndDate"=>"31/12/2013",
)
);
try{
$response = $client->__soapCall("CreateRebillEvent", $bodyoptions2,NULL,$header,$outputHeader);
//echo $client->__getLastRequest();
//print_r($response);
echo "<br/>";
echo $result2 = $response->CreateRebillEventResult->Result;echo "<br/>";
echo $RebillCustomerID = $response->CreateRebillEventResult->RebillCustomerID;echo "<br/>";
if($result2=='Success'){
echo 'Recurring Cycle Created Successfully at eWay!...<br/>';
echo 'Member Id is ===>'.$RebillCustomerID;
//$UpdateRebillCustomer = CreateRebillEvent($customerId);
//print_r($UpdateRebillCustomer);
}
else{
echo $ErrorSeverity = $response->CreateRebillEventResult->ErrorSeverity;echo "<br/>";
echo $ErrorDetails = $response->CreateRebillEventResult->ErrorDetails;echo "<br/>";
}
}
catch(SOAPFault $e){
print $e;
}
}
?>

If you are writing a client for a SOAP service and you want to manipulate or test their response by placing it in a local file and parsing that (maybe their response has errors and you want to fix the errors yourself), you can override the URL that your soapClient uses to call methods by calling __soapCall() directly:
$result = $this->soap_client->__soapCall( 'function_call_name', ['location' => $file_location] );
Where $file_location is the absolute or relative path to your copy of their xml response. What you put as your function call name doesn't matter, since the soap client will get the same xml response regardless of what function you try to call this way. The only thing that matters is that your $file_location be correct and that the xml file has the correct permissions to be read by apache if you run this in a browser.
You can then var_dump($response) and find the node you need rather than using simplexml_load_string. If you do it this way you can easily swap out your xml for their response later on.

Related

Passing Array via SOAP for SAP Webservice

I am trying to pass a 2D Array via SOAP for SAP Webservice.
But I am unable to pass the same.
I am able to pass a value, also I am able to accept a table output from SAP.
Please guide.
I tried to typecast array as an object.
My Code:
<?php
include("include/config.php");
$sql = "SELECT tid,OrderNumber FROM transhistory ORDER by timestamp ASC limit 2";
$result= mysqli_query($db,$sql);
$i=0;
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
//Array based on output table
$pmt[$i][0] = ""; //Mandt
$pmt[$i][1] = $row["tid"]; //Refnum
$pmt[$i][2] = $row["OrderNumber"]; //Orderno
$i++;
}
/*Two methods I tried */
$object = (object) $pmt;
$object = json_decode(json_encode($pmt), FALSE);
#Define Authentication
$SOAP_AUTH = array( 'login' => 'abc',
'password' => 'abc');
#Specify WSDL
$WSDL = "working URL here";
#Create Client Object, download and parse WSDL
$client = new SoapClient($WSDL,$SOAP_AUTH);
#Setup input parameters (SAP Likes to Capitalise the parameter names)
$params = array(
'Zpmt' => $object
);
#Call Operation (Function). Catch and display any errors
try {
$result = $client->ZphpOT($params);
} catch (SoapFault $exception) {
echo 'Error!Server Connectivity issue. Please try again later.';
die();
}
?>
I don't know if the answer may be useful for somebody but usually you send parameters like this
$result = $client->ZphpOT("VARIABLE_NAME"=>$params);

Error when i try to overview soap with php

Hello i have some request in soap but i have some error when i try the request in my website.
Fatal error: Call to a member function Body() on a non-object in /home/loraclec/public_html/pick5.php on line 14
Request :
<?php
/** define the SOAP client using the url for the service**/
$SoapiClient = new soapclient('http://14.141.212.201/ConRsltAPI/Result.asmx?WSDL', array('trace' => 1));
$lStrCred = "GI2304CON15";
$lStrGameName = "PICK3";
$lstrStatus = "0";
$thearray = array(
'lStrCred' => $lStrCred,
'lStrGameName' => $lStrGameName,
'lstrStatus' => $lstrStatus
);
$result = $client->Body($thearray);
if (is_soap_fault($result)):
echo '<h1>ERRROR</h1><pre>';
print_r($result);
echo '</pre>';
else:
echo '<h1>Working FINE</h1><pre>';
print_r($result);
echo '</pre>';
endif;
// see the last SOAP request
echo htmlspecialchars($client->__getLastRequest(), ENT_QUOTES);
// print the SOAP response
echo htmlspecialchars($client->__getLastResponse(), ENT_QUOTES);
/** lets store the login token just in case we want to use it for later use**/
$token = $result->token;
?>
$client doesn't exist on line 14. Change:
$result = $client->Body($thearray);
to
$result = $SoapiClient->Body($thearray);

Sending arrays with SOAP using PHP

Hopefully anybody can help me with PHP to successfully parse the XML? That’s my problem. I get back XML on the wire, but PHP doesn’t parse it.
Neither PHP-SOAP/5.2.17 nor PHP-SOAP/5.1.6, haven’t tried yet on PHP 5.3.
<?PHP
echo "<html><body>\n";
echo "starting<br>\n";
echo "<pre>\n";
$wsdl = "http://192.168.16.7/api/soap/softswitch.wsdl";
ini_set("soap.wsdl_cache_enabled", "0"); // disable WSDL cache
$client = new SoapClient($wsdl, array('trace'=>true, 'exceptions'=>true));
try {
$response = $client->get_queue_destinations($_REQUEST['username'],
$_REQUEST['password'], $_REQUEST['queue']);
# echo "$response";
print_r($response);
# var_dump($response);
$x = serialize($client->__getLastResponse());
print_r($x);
#$xml = simplexml_load_string($client->__getLastResponse());
#print_r($xml);
# print "Request: \n".htmlentities($client->__getLastRequest()) ."\n";
# print "Response: \n".htmlentities($client->__getLastResponse())."\n";
# echo "</pre>\n";
} catch (Exception $e) {
echo "<pre>\n";
echo "Caught Exception: " . $e->getMessage() . "\n";
// Show the actual XML sent and received
print "Request: \n".$client->__getLastRequest() ."\n";
print "Response: \n".$client->__getLastResponse()."\n";
echo "</pre>\n";
}
echo "</pre>\n";
echo "finished\n";
echo "</body><html>\n";
?>
visit http://us2.php.net/serialize
"serialize function cannot be used for xml parsing"
#$xml = simplexml_load_string($client->__getLastResponse());
#print_r($xml);
Simple XML is an object and it cannot be print_r in that way.

Reading Web Service using PHP with GUID and Namespace

I am new to Web Services and am struggling to access/read the XML data using PHP (my website that will be using the data is in PHP).
The WSDL Url: http://services.mywheels.co.za/BWAVehicleStockService.svc?wsdl
I need to get access and read the Vehicle stock information but cant see to access anything.
the Array vehicle are stored under: http://services.mywheels.co.za/BWAVehicleStockService.svc?xsd=xsd2 .
i am using this code but it doesnt give my any data. I also have a GUID that i need to pass but have no idea how to add it to the header.
<?PHP
define('NEWLINE', "<br />\n");
// SOAP client
$wsdl = 'http://services.mywheels.co.za/BWAVehicleStockService.svc?wsdl';
$soapClient = new SoapClient($wsdl, array('cache_wsdl' => 0));
// SOAP call
$parameters->ArrayOfVehicle->Vehicle;
try
{
$result = $soapClient->GetVehicleStock($parameters);
}
catch (SoapFault $fault)
{
echo "Fault code: {$fault->faultcode}" . NEWLINE;
echo "Fault string: {$fault->faultstring}" . NEWLINE;
if ($soapClient != null)
{
$soapClient = null;
}
exit();
}
$soapClient = null;
echo "<pre>\n";
print_r($result);
echo "</pre>\n";
echo "Return value: {$result->GetDataResult}" . NEWLINE;
?>
if someone can help or point me in the right direction with this that would be great.
Thanks
You can add headers using __setSoapHeaders():
$h = new SoapHeader('http://tempuri.org/', 'Guid', '123');
$soapClient->__setSoapHeaders($h);
I had to read the WSDL itself to find out what namespace I should use; in this case they refer to Guid as tns:Guid and from the top you can read what URI is used to express that, hence http://tempuri.org.

Why cant php work with WCF 4.0 asp website with a WCF service work?

Ok my .net 4.0 client works fine. People using java all have no issues. But when it comes to php our php developer cant get anything to work.
Now keep in mind i did not create a Wcflibray project, i created a regular asp 4.0 website and then added a WCF Service so i do not have a app.config, i have a web.config.
We have went down to the bare essentials of creating two methods
string HelloWorld()
{
return "Hello!";
}
and
string HellowTomorrow(string sret)
{
return sret;
}
In debug mode i will see him enter my method but only with null. If i packet sniff with wireshark, he is not passing the paramater envelope.
I have googled endlessly but all examples are from a WCF service project, not a website that has added a WCF Service too it. (rememember, everyone else is having no problems, java, .net 2.0, etc)
Here is his php 5.3
error_reporting(E_ALL);
ini_set('display_errors','On');
$client = new SoapClient("http://99-mxl9461k9f:6062/DynamicWCFService.svc?wsdl", array('soap_version' => SOAP_1_1));
$client->soap_defencoding = 'UTF-8';
//$args = array('john');
$args = array('param1'=>'john');
$webService = $client->__soapCall('HelloTomorrow',$args);
//$webService = $client->HelloTomorrow($args);
var_dumpp($webService);
?>
While working with WCF service .net as Server and PHP-soap as client you need to follow guideline strictly. The documentation of PHP-soap is not enough to debug and not that clear either. PHP nusoap is little better on documentation but still not enough on example and not a great choice for the beginners. There are a few examples for nusoap but most of them don’t work.
I would suggest following debug checklist:
Check the binding in your web.config file. It has to be “basicHttpBinding” for PHP
PHP, $client->__soapCall() function sends all arguments as an array so if your web-service function require input parameters as an array then arguments has to be in an extra array. Example#3 is given below to clear.
If required then pass “array('soap_version' => SOAP_1_1)” or “array('soap_version' => SOAP_1_2)” to SoapClient() object to explicitly declare soap version.
Always try declaring “array( "trace" => 1 )” to SoapClient Object to read the Request & Response strings.
Use “__getLastResponse();” function to read Response String.
Use “__getLastRequest();” function to read Request String.
IMPORTANT:If you are getting NULL return for any value passed as
parameter then check your .cs(.net) file that look like this:
[ServiceContract]
public interface IDynamicWCFService
{
[OperationContract]
string HelloYesterday(string test);
}
The variable name passes here, have to match with when you call it in PHP. I am taking it as “test” for my examples below.
Example #1: using php-soap with single parameter for HelloYesterday function
<?php
$url="http://99-mxl9461k9f:6062/DynamicWCFService.svc?WSDL";
$client = new SoapClient($url, array( "trace" => 1 ));
$result = $client->HelloYesterday(array('test' => 'this is a string'));
var_dump($result);
$respXML = $client->__getLastResponse();
$requXML = $client->__getLastRequest();
echo "Request: <br>";
var_dump($requXML);
echo "Response: <br>";
var_dump($respXML);
?>
Example #2 : using nusoap with single parameter for HelloYesterday function
<?php
require_once('../lib/nusoap.php');
$proxyhost = isset($_POST['proxyhost']) ? $_POST['proxyhost'] : '';
$proxyport = isset($_POST['proxyport']) ? $_POST['proxyport'] : '';
$proxyusername = isset($_POST['proxyusername']) ? $_POST['proxyusername'] : '';
$proxypassword = isset($_POST['proxypassword']) ? $_POST['proxypassword'] : '';
$url="http://99-mxl9461k9f:6062/DynamicWCFService.svc?WSDL";
$client = new nusoap_client($url, 'wsdl', $proxyhost, $proxyport, $proxyusername, $proxypassword); $client->soap_defencoding = 'UTF-8'; // this is only if you get error of soap encoding mismatch.
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
// Doc/lit parameters get wrapped
$param = array('test' => ' This is a string for nusoap');
$result = $client->call('HelloYesterday', array('parameters' => $param), '', '', false, true);
// Check for a fault
if ($client->fault) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
// Check for errors
$err = $client->getError();
if ($err) {
// Display the error
echo '<h2>Error</h2><pre>' . $err . '</pre>';
} else {
// Display the result
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
}
echo '<h2>Request</h2><pre>' . htmlspecialchars($client->request, ENT_QUOTES) . '</pre>';
echo '<h2>Response</h2><pre>' . htmlspecialchars($client->response, ENT_QUOTES) . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->debug_str, ENT_QUOTES) . '</pre>';
?>
One more example… passing array as a parameter or pass mixed type parameter then check the following example:
Example #3: passing mixed type parameter including array parameter to Soap function.
Example of .net operation file
[ServiceContract]
public interface IDynamicWCFService
{
[OperationContract]
string[] HelloYesterday (string[] testA, string testB, int testC );
}
PHP code
<?php
$url="http://99-mxl9461k9f:6062/DynamicWCFService.svc?WSDL";
$client = new SoapClient($url, array( "trace" => 1 ));
$params = array(
"testA" => array(0=>"Value1",1=>"Value2",2=>"Value3"),
"testB" => “this is string abc”,
"testC" =>123
); // consider the first parameter is an array, and other parameters are string & int type.
$result = $client->GetData($params);
var_dump($result);
$respXML = $client->__getLastResponse();
$requXML = $client->__getLastRequest();
echo "Request: <br>";
var_dump($requXML);
echo "Response: <br>";
var_dump($respXML);
?>
Hope the above examples will help.
Since you're passing the wsdl location into the SoapClient constructor, you should be able to call $client->HelloTomorrow($args). There seem to be a few typos, though, can you verify that they are all correct in your actual code? In your web service code, you name the function HellowTomorrow but you're calling HelloTomorrow in your PHP code. Also, the parameter is named sret in your web service, but it's being passed as param1 in the $args associative array. Does it work calling HelloWorld() which doesn't expect any parameters?
Update:
See NuSOAP and content type
Try using the built-in PHP SoapClient instead of the NuSOAP version. PHP's SoapClient looks like it defaults to UTF-8, where NuSOAP seems to be hard-coded to ISO-8859-1

Categories