Sending arrays with SOAP using PHP - 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.

Related

Parse SendGrid JSON with PHP

I have some simple JSON data returned by the SendGrid API:
{
"message":"error",
"errors":[
"some errors"
]
}
I can access the contents of the "message" section via:
$txt = "{\"message\":\"success\"}";
$newtxt = json_decode($txt, true);
echo $newtxt['message'];
That works okay, but I can't work out how to access the contents of the "errors" section?
Sorry, I realise this is probably a silly question.
If your JSON String is this
$tst = '{
"message":"error",
"errors":[
"some errors"
]
}';
Then all you need to so is
$j_array = json_decode($txt, true);
echo $j_array['message'];
echo $j_array['errors'][0];
A better way would be to loop over this array
foreach ($j_array['errors'] as $error ) {
echo $error . '<br>';
}
Of course you dont need to convert everything to an array, you can leave it as written i.e. an object containing properties one of which is an array
$jObj = json_decode($txt);
echo $jObj->message;
echo $jObj->errors[0];
Or
foreach ($jObj->errors as $error ) {
echo $error . '<br>';
}

PHP SoapClient __getLastRequest and __getLastRequestHeaders return NULL for successful call

I'm going through tutorials on webservices and SOAP. In learning about these, I created a php file to act on the WSDL provided by w3schools that converts temperatures between Celsius and Fahrenheit.
I wrote the following PHP code which fires successfully:
$wsdl = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
$soapClient = new SoapClient($wsdl);
// print_r ($soapClient->__getFunctions());
// print_r ($soapClient->__getTypes());
$parameters = array("Celsius" => "0");
$result = $soapClient->__soapCall("CelsiusToFahrenheit", array($parameters) );
echo "key: " . key($result) . "<br />" ;
echo "value: " . current($result) . "<br />" ;
The browser successfully returns the following:
key: CelsiusToFahrenheitResult
value: 32
I then tried to use the SoapClient methods __getLastRequest() and __getLastRequestHeaders() to take a look at the headers that were sent and see how they compare to what I had been reading and both method calls returned null
echo "Last call headers: <br />";
echo $soapClient->__getLastRequestHeaders();
echo "<br />" ;
echo "Last call headers: <br />";
echo $soapClient->__getLastRequest();
I reviewed the notes and example in the php manual for _getLastRequestHeaders() and it looks like everything is set up correctly. I can't tell what I'm doing wrong :/
Any help would be appreciated!
If you don't set trace to true in the options argument of the constructor of the SoapClient, it won't store these. So simply put, this will work for you:
$soapClient = new SoapClient($wsdl, array('trace' => true));
... which the manual page you linked to explicitly states:
Note:
This function only works if the SoapClient object was created with the trace option set to TRUE.

How to read soap response xml in 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.

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.

Microsoft CRM 3.0 web service via PHP Soap class

I would like to create new contacts and leads using php. I can't quite figure out how to call the methods of the mscrm 3 web service.
The php soap class seems quite simple to use. I am able to connect and authenticate to the crm web service and get a list of available functions however I am unsure how to go about calling them.
I have seen examples for mscrm 4.0 which seem to involve masses of XML including soap headers and envelopes.
I am under the impression that using a soap class bypasses this and will write all the extra xml for me so all I need to do is call a function with an array of parameters?
Am I completely wrong here ?
Has anyone done this with mscrm 3 that can provide some sample code, or perhaps give me a few pointers as how to correctly call the Create() method ?
I have been able to get this working by using Nusoap and after construction the XML message as a series of strings using the send method instead of call. This now works as expected. It seemed that using the call method was returning different XML than what was required by the ms crm 3 web service.
Any decent SOAP toolkit will automagically spit out the correct XML. Check out this guy:
http://us2.php.net/xmlrpc_encode_request
require_once ('/var/mtp/lib/vendor/nusoap/lib/nusoap.php');
$login ='domain\username';
$pass ='password';
$useCURL = true;
$client = new nusoap_client('http://server:5555/mscrmservices/2006/crmservice.asmx?wsdl', 'wsdl');
$client->setCredentials($login, $pass, 'ntlm');
$client->setUseCurl($useCURL);
$client->useHTTPPersistentConnection();
$client->soap_defencoding = 'UTF-8';
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
echo '<h2>Debug</h2><pre>' . htmlspecialchars($client->getDebug(), ENT_QUOTES) . '</pre>';
exit();
}
$soapHeader='<soap:Header>' .
'<CallerId xmlns="http://schemas.microsoft.com/crm/2006/WebServices">'.
'<CallerGuid xmlns="http://schemas.microsoft.com/crm/2006/CoreTypes">00000000-0000-0000-0000-000000000000</CallerGuid></CallerId>' .
'</soap:Header>';
$soapBody='<soap:Body>' .
'<entity xmlns="http://schemas.microsoft.com/crm/2006/WebServices" xsi:type="lead">' .
'<ownerid type="Owner">2408c7dc-c0a3-dd11-b3cd-001a4bd3009a</ownerid>' .
'<firstname>Fred</firstname>' .
'<lastname>Bloggs</lastname>' .
'</entity>' .
'</soap:Body>';
$xml = '<?xml version="1.0" encoding="utf-8"?>' .
'<soap:Envelope' .
' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' .
' xmlns:xsd="http://www.w3.org/2001/XMLSchema"' .
' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' .
$soapHeader .
$soapBody .
'</soap:Envelope>';
//SOAP call
$result = $client->send($xml,'http://schemas.microsoft.com/crm/2006/WebServices/Create' );
//result
if ($client->fault) { //check for fault
echo '<p><b>Fault: ';
print_r($result);
echo '</b></p>';
}
else { //no fault
$err = $client->getError();
if ($err) { // error
echo 'Error: ' . $err . '';
echo "\n\n# # # # # # # Request # # # # # # #\n";
var_dump($client->request);
echo "\n\n# # # # # # Response # # # # # # #\n";
var_dump($client->response);
}
else { // display the result
print_r($result);
}
}
I was also struggling to get Dynamics CRM SOAP working with PHP but after a while I managed to get it working; http://www.ifc0nfig.com/working-with-microsoft-dynamics-crm-4-0-soap-interface-with-php-and-nusoap/ - You can download a small class I created which may be of use :)

Categories