I've had some difficulty finding resources on this, to connect to a SOAP API using PHP and easily attach the array results to variables for display purposes.
Here is the SOAP API XML of GetCostCenters function within the API:
<Response><Status><Result>1</Result><Description>OK</Description></Status><CostCenters><CostCenter><ID>4</ID><Branch>Adelaide</Branch></CostCenter><CostCenter><ID>6</ID><Branch>Derby</Branch></CostCenter><CostCenter><ID>33</ID><Branch>GT Perth</Branch></CostCenter><CostCenter><ID>7</ID><Branch>Hobart Branch</Branch></CostCenter><CostCenter><ID>46</ID><Branch>Lawns & Maintenance</Branch></CostCenter><CostCenter><ID>10</ID><Branch>London</Branch></CostCenter><CostCenter><ID>3</ID><Branch>Melbourne</Branch></CostCenter><CostCenter><ID>45</ID><Branch>NECA Apprentices</Branch></CostCenter><CostCenter><ID>17</ID><Branch>New York</Branch></CostCenter><CostCenter><ID>48</ID><Branch>Nursing NSW</Branch></CostCenter><CostCenter><ID>1</ID><Branch>Perth</Branch></CostCenter><CostCenter><ID>44</ID><Branch>Registration</Branch></CostCenter><CostCenter><ID>16</ID><Branch>Rio</Branch></CostCenter><CostCenter><ID>50</ID><Branch>Subiaco</Branch></CostCenter><CostCenter><ID>51</ID><Branch>Subiaco</Branch></CostCenter><CostCenter><ID>2</ID><Branch>Sydney</Branch></CostCenter><CostCenter><ID>42</ID><Branch>test - tester</Branch></CostCenter><CostCenter><ID>49</ID><Branch>TesterOM</Branch></CostCenter><CostCenter><ID>8</ID><Branch>Tom Price</Branch></CostCenter><CostCenter><ID>47</ID><Branch>Traffic Control NSW</Branch></CostCenter></CostCenters></Response>
Here is my PHP:
$client = new SoapClient("https://api.myfeed.com/feed.asmx?WSDL", array(
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
// GET RESULTS
$result = $client->GetCostCenters(array(
'CompanyID' => 'MYID',
'APIKey' => 'MYKEY',
'APIPassword' => 'MYPASS',
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
echo '<pre>';
print_r($result);
echo '</pre>';
Outputs it all on one line in [any] like this:
stdClass Object
(
[GetCostCentersResult] => stdClass Object
(
[any] => 1OK4Adelaide6Derby33GT Perth7Hobart Branch46Lawns & Maintenance10London3Melbourne45NECA Apprentices17New York48Nursing NSW1Perth44Registration16Rio50Subiaco51Subiaco2Sydney42test - tester49TesterOM8Tom Price47Traffic Control NSW
)
)
and I can't figure out why, ideally I want it as an array so I can assign variables and run a loop to display the information.
Any ideas? Thanks in advance.
Convert the result from string to xml object (simplexml_load_string):
$resultAsXml = simplexml_load_string($result);
Then convert the object to array using the json encoding (json_encode, json_decode):
$resultAsArray = json_decode(json_encode($resultAsXml), true);
Note the second argument passed to json_decode:
When true, JSON objects will be returned as associative arrays;
In your case:
$client = new SoapClient("https://api.myfeed.com/feed.asmx?WSDL", array(
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
// GET RESULTS
$result = $client->GetCostCenters(array(
'CompanyID' => 'MYID',
'APIKey' => 'MYKEY',
'APIPassword' => 'MYPASS',
'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
'trace' => true
));
$resultAsXml = simplexml_load_string($result);
$resultAsArray = json_decode(json_encode($resultAsXml), true);
echo '<pre>';
print_r($resultAsArray);
echo '</pre>';
Related
I am trying to get Polly to read something for me, using PHP.
I have created a new project, installed Amazon composer require aws/aws-sdk-php and then created a file with code from SDK documentation example and modified a few minor things such as changing credential from default to value, var_dump to var_export and finally saved the content of the stream to file
<?php
require 'vendor/autoload.php';
use Aws\Exception\AwsException;
use Aws\Polly\PollyClient;
use Aws\Credentials\Credentials;
// Create a PollyClient
$client = new Aws\Polly\PollyClient([
//'profile' => 'default',
'credentials' => new Credentials('XXXXXXXXXXXXXXXXXXXX', 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'),
'version' => '2016-06-10',
'region' => 'us-east-2'
]);
try {
$result = $client->synthesizeSpeech([
'Text' => 'Hello',
'OutputFormat' => 'json', //json|mp3|ogg_vorbis|pcm
'VoiceId' => 'Joanna',
]);
var_export($result);
$data = $result->get('AudioStream')->getContents();
echo "\n\n";
var_export($data);
$file = fopen('test.txt','w+');
fwrite($file,$data);
fclose($file);
} catch (AwsException $e) {
echo $e->getMessage() . "\n";
}
The result I'm getting is following
Aws\Result::__set_state(array(
'data' => array (
'AudioStream' => GuzzleHttp\Psr7\Stream::__set_state(array(
'stream' => NULL,
'size' => NULL,
'seekable' => true,
'readable' => true,
'writable' => true,
'uri' => 'php://temp',
'customMetadata' => array (),
)),
'ContentType' => 'application/x-json-stream',
'RequestCharacters' => '5',
'#metadata' => array (
'statusCode' => 200,
'effectiveUri' => 'https://polly.us-east-2.amazonaws.com/v1/speech',
'headers' => array (
'x-amzn-requestid' => 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
'x-amzn-requestcharacters' => '5',
'content-type' => 'application/x-json-stream',
'transfer-encoding' => 'chunked',
'date' => 'Sat, 18 Sep 2021 05:11:20 GMT',
),
'transferStats' => array (
'http' => array (
0 => array (),
),
),
),
),
'monitoringEvents' => array (),
))
''
As you can see the size of the AudioStream is null (nothing in it) and also the created file is also empty since there is nothing in the stream to read.
If I change a credential to an invalid string, I get errors, and with the valid credential, the status code is 200, which makes me believe that my request is successful.
I changed voiceId to any other valid or invalid id and even changed the region with others with valid values getting status 200 and with invalid ones getting error messages, but I'm still not getting anything out of polly, it doesn't feel like talking!
Note: When I run $arr_voices = $polly->describeVoices();, I can read list of the voices without error.
Note: I had the same issue with .NET SDK too, which makes me think either there is something wrong with my request or some error message is missing from API.
Question
What I'm doing wrong?
You're not doing anything wrong, but it only outputs JSON if you're looking for speech marks. Try switching to an audio output format like MP3 as shown below.
$result = $client->synthesizeSpeech([
'Text' => 'Hello',
'OutputFormat' => 'mp3', //json|mp3|ogg_vorbis|pcm
'VoiceId' => 'Joanna',
]);
If you're looking for speech marks- metadata on the speech that will be synthesized- you need to specify SpeechMarkTypes as shown here https://docs.aws.amazon.com/aws-sdk-php/v3/api/api-polly-2016-06-10.html#synthesizespeech
It tells me that Object reference not set to an instance of an object, when trying to call this SOAP API.
I am doing this way
$client = new SoapClient("http://gateway.XXXXXXX/gateway/api/creditcards/creditcardAPI.asmx?wsdl");
$params = array("clsCreditCardAPIBE" => (Object) array(
"Username" => 'blabla',
"Password" => "Barrel of Oil",
"ProviderPIN" => 500,
"AccountID" => 1234
.......
));
$response = $client->__soapCall("Initiate_Deposit", $params);
What am i doing wrong?
You have to generate the client first, and then start using it
$client = new SoapClient("http://yourdomain.com?wsdl");
Before starting, I know, this errors means that I should have defined the property FinalBookingDate, but just keep reading and you will understand my point of view.
The url is: http://bestbuyhotel1.cangooroo.net/ws/2013/ClientBackOffice_b.asmx?op=getBookingList
I was testing first with SoapUi, and I successfull get the list that I need:
And on php, I only can get this response:
The SoapClient from php is:
$params = array('soap_version' => SOAP_1_2, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'encoding'=>'UTF-8', 'trace' => 1, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE, 'features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new \SoapClient('http://bestbuyhotel1.cangooroo.net/ws/2013/ClientBackOffice_b.asmx?wsdl', $params);
And then, the code to retrieve the data:
/*
$query = array(
'InitialServiceDate' => '2015-01-20',
'InitialBookingDate' => '2015-01-20',
'FinalBookingDate' => '2015-01-20',
'FinalServiceDate' => '2015-01-20',
'CreationUserId' => 1338,
'CityId' => 4166,
'ServiceTypes' => array('eServiceType' => 'HOTEL')
);
*/
$query = array(
'InitialBookingDate' => '2015-01-20',
'ServiceTypes' => array('eServiceType' => 'HOTEL')
);
$args = new \stdClass;
$args->credential = new \stdClass;
$args->credential->UserName = $conn['userPass']['usr'];
$args->credential->Password = $conn['userPass']['pass'];
$args->searchBookingCriteria = new \stdClass;
$args->searchBookingCriteria->InitialBookingDate = '2015-01-20';
$args->searchBookingCriteria->ServiceTypes = new \stdClass;
$args->searchBookingCriteria->ServiceTypes->eServiceType = 'HOTEL';
//$args = array('credential'=>$credentials, 'searchBookingCriteria' => $query);
$data = $conn['client']->getBookingList($args);
print_r($data);
exit;
As you can see, I tried 2 ways to send the $args to getBookingList, as far I know both of then is valid and yet both of then (with array or object) return the same error. On the code commented at first you can see that I tried to define all does properties that the web service asks but after defining all of then I get a empty result.
My question is, there is some extra param to define on SoapClient that I should do? Why the SoapUI can do it with success? What I have missing here?
Bonus: A print of SoapUI full screen with the default request including the optional params https://www.evernote.com/shard/s14/sh/fb5ac276-8147-4e09-95bb-afa0be66d7a6/d273441c74186bf1e600b42ab3303899/deep/0/SoapUI-5.0.0.png
Can you try this more direct approach:
try {
$params = array('soap_version' => SOAP_1_2, 'compression' => SOAP_COMPRESSION_ACCEPT | SOAP_COMPRESSION_GZIP, 'encoding'=>'UTF-8', 'trace' => 1, 'exceptions' => true, 'cache_wsdl' => WSDL_CACHE_NONE, 'features' => SOAP_SINGLE_ELEMENT_ARRAYS);
$client = new SoapClient('http://bestbuyhotel1.cangooroo.net/ws/2013/ClientBackOffice_b.asmx?wsdl',$params);
} catch (SoapFault $E) {
echo $E->faultstring;
}
if ($client) {
$req_params = array('credential' =>
array('userName' => 'XXXXXXX',
'Password' => 'XXXXXXX'),
'searchBookingCriteria' =>
array('BookingNumber' => array('int' => 'XXXXXXXXX'),
'ServiceTypes' => array('eServiceType' => 'HOTEL'),
'PassengerName'=> 'XXXXXXXX',
'InitialBookingDate'=> '2015-01-16',
'FinalBookingDate'=> '2015-01-16',
'InitialServiceDate' => '2015-01-18',
'FinalServiceDate' => '2015-01-18',
'BookingStatus'=> array('eStatus' => 'ACTIVATED'),
'PaymentStatus'=> array('ePaymentStatus' => 'Payed'),
'CreationUserId'=> 'XXX',
'CityId'=> 'XXXX',
'ExternalReference'=> '')
);
$response = $client->__soapCall('getBookingList',array($req_params));
var_dump($response);
}
Try (and add) this approach:
$args->searchBookingCriteria->FinalBookingDate = '2015-01-22';
$args->searchBookingCriteria->InitialServiceDate = '2015-01-22';
$args->searchBookingCriteria->FinalServiceDate = '2015-01-22';
$args->searchBookingCriteria->CreationUserId = 'abc';
$args->searchBookingCriteria->CityId = 'abc';
I am doing a PHP SOAP Request as follows (my code, location removed as I'm not allow to publish)
try {
$location = "http://myUrltoWSDLhere";
$client = new SoapClient($location,
array(
'soap_version' => SOAP_1_1,
'login' => 'myuser',
'password' => 'mypass'
));
$params = array(array('BUKRS'=> 1));
$x = $client->ZIbFtiWsCredPosToWeb( $params );
print_r($x);
} catch (Exception $e) {
echo $e->getMessage();
}
I've been trying countless combinations how to pass the params to my method and I am doing a print_r($x) and gives me the below output.
stdClass Object ( [EBkpf] => stdClass Object ( ) [EMsgnr] => 6 [EMsgtxt] => BUKRS is missing [EMsgtyp] => E [ESstMon] => 00000000000000000000 )
Important: SoapClient getTypes returns the following for this method and the IBukrs is the field I am trying to pass data to. In SAP the Company Code is "BUKRS" so I had tried BUKRS and IBukrs and also Bukrs.
Any help would be greatly appreciated!!
[43] => struct ZIbFtiWsCredPosToWeb {
int IAnz;
char1 IAp;
char4 IBukrs;
ZibSstGjahr IGjahr;
ZibSstCredTt IKreditor;
char1 IOp;
numeric20 ISstMon;
}
WSDL Content: http://pastebin.com/fU5PhD9B
I am pulling some emails from my mail server. There is a function should pull these emails and return a multidimensional array. I use this array in client web server to do the job for me. I don't know how to pass this array to the soap complexType. I wrote the following code:
$server->wsdl->addComplexType(
'MailTicket',
'complexType',
'struct',
'all',
'',
array(
'attachment' => array('name' => 'attachment', 'type' => 'xsd:string'),
'body' => array('name' => 'body', 'type' => 'xsd:string'),
'accountID' => array('name' => 'accountID', 'type' => 'xsd:string')
)
);
$server->wsdl->addComplexType(
'MailTicketReturn',
'complexType',
'struct',
'all',
'',
array(
'Done' => array('name' => 'result', 'type' => 'xsd:string')
)
);
// Register the method to expose
$server->register('createMailTicket', // method name
array('mailTicketData' => 'tns:MailTicket'), // input parameters
array('return' => 'tns:MailTicketReturn'), // output parameters
'urn:eticketing', // namespace
'urn:eticketing#createMailTicket', // soapaction
'rpc', // style
'encoded', // use
'create a ticket by mail' // documentation
);
and on the client, I wrote:
require_once('nusoap.php');
$wsdlURL="http://127.0.0.1/eticket/ETKWS.php?wsdl";
$client = new nusoap_client($wsdlURL,true);
$client->soap_defencoding = 'UTF-8';
$client->decode_utf8 = false;
$finalArray=Array
(
[attachment] => Array
(
[0] => Array
(
[0] => file1
[1] => file2
)
[1] => Array
(
[0] => file1x
)
)
[body]=>Array
(
[0] => some text
[1] => some other text
)
[accountID] => Array
(
[0] => 5464654
[1] => 4654664
)
)
if(is_array($finalArray)) // creat new tickets
{
$result=$client->call('createMailTicket',$finalArray);
}
$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();
}
I got this error:
Constructor error
XML error parsing SOAP payload on line 1: Not well-formed (invalid token)
NuSOAP support return multidimensional array (xsd:Array)
$server= new nusoap_server();
$namespace = "http://localhost/webservice/";
// create a new soap server
$server = new nusoap_server();
// configure our WSDL
$server->configureWSDL("WebServices212");
// set our namespace
$server->wsdl->schemaTargetNamespace = $namespace;
$server->register(
// method name:
'test',
// parameter list:
array('id'=>'xsd:int'),
// return value(array()):
array('return'=>'xsd:Array'),
// namespace:
$namespace,
// soapaction: (use default)
false,
// style: rpc or document
'rpc',
// use: encoded or literal
'encoded',
// description: documentation for the method
'documentation');
$POST_DATA = isset($GLOBALS['HTTP_RAW_POST_DATA'])
? $GLOBALS['HTTP_RAW_POST_DATA'] : '';
// pass our posted data (or nothing) to the soap service
$server->service($POST_DATA);
Client
client=new nusoap_client("http://localhost/webservice /webservices.php?wsdl");
$client->setCredentials("webadmin","****");
$err = $client->getError();
if ($err) {
echo '<h2>Constructor error</h2><pre>' . $err . '</pre>';
}
$result = $client->call('test', array('id' => '1'));
print_r($result);
if you consume the webservices from PHP no problem, but in other languages there are compatibility problems