Send an XML file via POST [duplicate] - php

I need to send this XML
<?xml version="1.0" encoding="UTF-8"?>
<gate>
<country>NO</country>
<accessNumber>1900</accessNumber>
<senderNumber>1900</senderNumber>
<targetNumber>4792267523</targetNumber>
<price>0</price>
<sms>
<content><![CDATA[This is a test æøå ÆØÅ]]></content>
</sms>
</gate>
to a SMS gateway service. The service listens for HTTP POST requests. The XML must be embedded in the BODY of the POST request.
I'm using PHP and the CodeIgniter framework, but I'm a total PHP n00b, so ideally I'd need a thorough guide, but any pointers in the right direction would be appreciated.

you can use cURL library for posting data:
http://www.php.net/curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);
where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

Another option would be file_get_contents():
// $xml_str = your xml
// $url = target url
$post_data = array('xml' => $xml_str);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
'content' => http_build_query($post_data)));
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

Related

FreeAgent oAuth2 can't update contact using Light PHP wrapper

I’m having problems creating a new contact in FreeAgent.
I’m using the Light PHP wrapper for the OAuth 2.0 protocol and have managed to successfully set up oAuth2. I can connect to FreeAgent and successfully retrieve a list of customers. So far, so good. The problem I’ve got is sending data back the other way, i.e. creating a new contact in FreeAgent.
Here’s some code I’ve tried:
require_once($_SERVER['DOCUMENT_ROOT'].'/OAuth2/Client.php');
require_once($_SERVER['DOCUMENT_ROOT'].'/OAuth2/GrantType/IGrantType.php');
$client = new OAuth2\Client($clientid, $secret);
$params = json_encode(array('contact' => array('first-name' => $firstname_unencrypted, 'last-name' => $surname_unencrypted)));
$response = $client->fetch("/contacts", $params, "POST", array('User-Agent' => 'MyApp', 'Accept' => 'application/json', 'Content-type' => 'application/json'));
var_dump($response);
The var_dump returned shows:
array(3) {
["result"]=>
bool(false)
["code"]=>
int(0)
["content_type"]=>
bool(false)
}
I’m pretty sure I’m doing something silly. I’ve tried sending in XML instead of JSON. I’ve tried using just a single array of params rather than the array in an array I’ve got in the sample. I’m going round in circles!
If someone could give me a little nudge in the right direction, I’d be eternally grateful!
Sample code that worked:
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<contact>
<first-name>$firstname_unencrypted</first-name>
<last-name>$surname_unencrypted</last-name>
</contact>";
if ($sandbox || $demo)
$ch = curl_init('https://api.sandbox.freeagent.com/v2/contacts');
else
$ch = curl_init('https://api.freeagent.com/v2/contacts');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$freeagentaccesstoken,
'Content-Type: application/xml',
'Accept: application/json',
'User-Agent: MyApp',
'Content-Length: ' . strlen($xml))
);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
//execute post
$result=json_decode(curl_exec($ch), true);
$freeagenturl=$result['contact']['url'];
curl_close($ch);

PHP xml SOAP and laravel

I have been trying to figure out how to make a soap request using php/laravel. But from all the research on internet since two days now the only things that I can find are old rusty php codes to make soap requests non of them even worked:
Here is a snipped that I am trying to make it work so I have a general view of those soap requests but I only get errors not able to make a soapclient:
<?php
$aHTTP['http']['header'] = "User-Agent: PHP-SOAP/5.5.11\r\n";
$aHTTP['http']['header'].= "username: XXXXXXXXXXX\r\n"."password: XXXXX\r\n";
$context = stream_context_create($aHTTP);
$client=new SoapClient("http://www.thomas-bayer.com/axis2/services/BLZService?wsdl",array('trace' => 1,"stream_context" => $context));
$result = $client::__getFunctions();
var_dump($result);
since it looks super hard to me to find any info about the soap with php any idea ?
This is a sample of a soap request I currently make to a payment provider via php using curl statements. Basically map the xml request you want to make in a string. The string will be sent in the curl post fields and the response returned.
$soapdata="<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tns='tns:ns'>
<soapenv:Header>
<tns:CheckOutHeader>
<MERCHANT_ID>$merchantid</MERCHANT_ID>
<PASSWORD>$password</PASSWORD>
<TIMESTAMP>$timestamp</TIMESTAMP>
</tns:CheckOutHeader>
</soapenv:Header>
<soapenv:Body>
<tns:processCheckOutRequest>
<MERCHANT_TRANSACTION_ID>$merchanttransactionid</MERCHANT_TRANSACTION_ID>
<REFERENCE_ID>$referenceid</REFERENCE_ID>
<AMOUNT>$amount</AMOUNT>
<MSISDN>$mobileno</MSISDN>
<!--Optional:-->
<ENC_PARAMS></ENC_PARAMS>
<CALL_BACK_URL>$callbackurl</CALL_BACK_URL>
<CALL_BACK_METHOD>$callbackmethod</CALL_BACK_METHOD>
<TIMESTAMP>$timestamp</TIMESTAMP>
</tns:processCheckOutRequest>
</soapenv:Body>
</soapenv:Envelope>";
//End Soap data
//We call the server for the first time
//end calling function
function makesoaprequest($url, $soapdata)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml', 'Authorization: Basic'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$soapdata");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//Begin SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
//End SSL
$response = curl_exec($ch);
return $response;
curl_close($ch);
}

How do I make a simple PHP API handler?

I've written a basic API script in PHP using cURL - and successfully used a version of it on another API, this one is specifically to handle domain DNS management on DigitalOcean - and I can't send data?
Prelude...
I understand there is a PHP library available, I'm not after something that full featured or bloated with dependencies - just something small to use locally and primarily to help me understand how RESTful API's work a little better in practice - an educational exercise
The offending Code...
function basic_api_handle($key, $method, $URI, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$key,
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
var_dump(basic_api_handle($api_key, 'POST', 'https://api.digitalocean.com/v2/domains', array('name' => 'my-domain.tld', 'ip_address' => '1.2.3.4')));
This works with a GET request, such as listing the domains on the account but seems to fail at posting/sending data... this results in "unprocessable_entity" and "Name can't be blank" - as the name is not blank and is correctly formatted (as far as I can tell) it suggests to me the data is not being sent correctly?
Solution Attempts so far...
I've tried json encoding the data (seen in code), not json encoding, url encoding with and without json encoding and various other options with no luck.
I've seen a few posts online about this exact same issue specifically with DigitalOcean's API (and a another) but no one had an explanation (other than give up and use the library or something to that affect).
Using cURL directly from a terminal does work etc so there is nothing wrong with the API for creating a domain.
As far as I understand, the authentication is working, and the general setup works as I can list domains within the account, I just cant POST or PUT new data. I've been though the API's documentation and can't see what I'm doing wrong, maybe some sort of wrong encoding?
Any help would be much appreciated! :)
Edit:
After much work and research even other simple API handlers do not work with Digital Ocean (such as https://github.com/ledfusion/php-rest-curl) - is there something this API in particular needs or am I missing something fundamental about API's in general?
Technically this is not an fix but a work around. Thank you everyone for your comments and ideas, unfortunately nothing worked/fixed the code and the bounty expired :(
Although I have no idea why the PHP cURL option didn't work (the HTTP works, just Digital Ocean spitting errors for unknown reason linked to validation of the post data)...
I do have a new method that DOES WORK finally... (thanks to jtittle post on the Digital Ocean Community forum)
Just incase that link dies in the future... he's the working function using streams and file_get_contents and not curl...
<?php
function doapi( $key, $method, $uri, array $data = [] )
{
/**
* DigitalOcean API URI
*/
$api = 'https://api.digitalocean.com/v2';
/**
* Merge DigitalOcean API URI and Endpoint URI
*
* i.e if $uri is set to 'domains', then $api ends up as
* $api = 'https://api.digitalocean.com/v2/domains'
*/
$uri = $api . DIRECTORY_SEPARATOR . $uri;
/**
* Define Authorization and Content-Type Header.
*/
$headers = "Authorization: Bearer $key \r\n" .
"Content-Type: application/json";
/**
* If $data array is not empty, assume we're passing data, so we'll encode
* it and pass it to 'content'. If $data is empty, assume we're not passing
* data, so we won't sent 'content'.
*/
if ( ! empty( $data ) )
{
$data = [
'http' => [
'method' => strtoupper( $method ),
'header' => $headers,
'content' => json_encode( $data )
]
];
}
else
{
$data = [
'http' => [
'method' => strtoupper( $method ),
'header' => $headers
]
];
}
/**
* Create Stream Context
* http://php.net/manual/en/function.stream-context-create.php
*/
$context = stream_context_create( $data );
/**
* Send Request and Store to $response.
*/
$response = file_get_contents( $uri, false, $context );
/**
* Return as decoded JSON (i.e. an array)
*/
return json_decode( $response, true );
}
/**
* Example Usage
*/
var_dump(doapi(
'do-api-key',
'get',
'domains'
));
I used this to actually post the data successfully...
var_dump(doapi(
$api_key,
'post',
'domains',
array("name" => (string) $newDomain, "ip_address" => "1.2.3.4")
));
Add the Content-Length header and use CURLOPT_POST option for POST requests
function basic_api_handle($key, $method, $URI, $data) {
$json = json_encode($data)
$headers = array(
'Authorization: Bearer '.$key,
'Content-Type: application/json'
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $URI);
if ( $method === 'POST' ) {
curl_setopt($curl, CURLOPT_POST, 1);
} else {
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
array_push($headers, 'Content-Length: ' . strlen($json) );
}
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers)
curl_setopt($ch, CURLOPT_POSTFIELDS, $json );
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
Maybe this will work for you:
function basic_api_handle($key, $method, $URI, $data) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method); // <-- Should be set to "GET" or "POST"
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // <-- Maybe the SSL is the problem
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"); // <-- I am not familiar with this API, but maybe it needs a user agent?
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer '.$key,
'Content-Type: application/json')
);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_URL, $URI);
curl_setopt($ch, CURLOPT_POST, count($data)); // <-- Add this line which counts the inputs you send
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
$result = curl_exec($ch);
if($result === false) error_log("API ERROR: Connection failure: $URI", 0);
curl_close($ch);
return json_decode($result, true);
}
It can also be a problem of a header you should sent and your missing it.
It could be a 307 or 308 http redirect.
Maybe "https://api.digitalocean.com/v2/domains" redirects to another url.
If this is the case, try adding:
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
to make curl follow the redirection and keep the parameters.
It is suggested that you also use:
curl_setopt($curl, CURLOPT_POSTREDIR, 3);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
to keep the request body.
Hope it helps.
You can also try use CURLOPT_POST

Sending Data Using Post Method Without Form

I want to send data to an API. The data include simple variables: username, password, email, etc.
The problem is that O want to send data to this using POST method. I searched this issue on Google, and everyone is saying to go for CURL.
What is CURL? Is it a function, script, API or what?
Is there any other way to do it?
I want to send something like this:
$username, $password to www.abc.com?username=$username&password=$password
Best Regards
By using this function you can send a post request with an optional number of
parameters. Just fill in the postdata array with key values pairs.
Example usage are provided.
<?php
function do_post_request($url, $postdata)
{
$content = "";
// Add post data to request.
foreach($postdata as $key => $value)
{
$content .= "{$key}={$value}&";
}
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/x-www-form-urlencoded',
'content' => $content
));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Connection problem, {$php_errormsg}");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Response error, {$php_errormsg}");
}
return $response;
}
// Post variables.
$postdata = array(
'username' => 'value1',
'password' => 'value2',
'param3' => 'value3'
);
do_post_request("http://www.example.com", $postdata);
?>
Simply use: file_get_contents()
// building array of variables
$content = http_build_query(array(
'username' => 'value',
'password' => 'value'
));
// creating the context change POST to GET if that is relevant
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'content' => $content, )));
$result = file_get_contents('http://www.example.com', null, $context);
//dumping the reuslt
var_dump($result);
cURL is a library "that allows you to connect and communicate to many different types of servers with many different types of protocols". So you can use cURL to send an HTTP POST request. Please read the PHP manual for detailed information: http://www.php.net/manual/en/book.curl.php
But cURL is not the only answer. You can use PHP Streams, or even connect to the webserver using socket functions and then generate your requests.
Personally I often use cURL because it's very flexible and you can work with cookies easily.
Php curl manual is a good starting point.
Following is an example of the usage of curl in php on Stackoverflow:
Send json post using php
The data set in an xml file:
$post="<?xml version="1.0\" encoding=\"UTF-8\"?>
<message xmlns=\"url\" >
<username>".$username."</username>
<password>".$password."</password>
<status date=\"2010-11-05 14:44:10+02\"/>
<body content-type=\"text/plain\">Noobligatory text</body>
</message>";
$url = "a-url-to-send-the-data";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
curl_close($ch);

How to post SOAP Request from PHP

Anyone know how can I post a SOAP Request from PHP?
In my experience, it's not quite that simple. The built-in PHP SOAP client didn't work with the .NET-based SOAP server we had to use. It complained about an invalid schema definition. Even though .NET client worked with that server just fine. By the way, let me claim that SOAP interoperability is a myth.
The next step was NuSOAP. This worked for quite a while. By the way, for God's sake, don't forget to cache WSDL! But even with WSDL cached users complained the damn thing is slow.
Then, we decided to go bare HTTP, assembling the requests and reading the responses with SimpleXMLElemnt, like this:
$request_info = array();
$full_response = #http_post_data(
'http://example.com/OTA_WS.asmx',
$REQUEST_BODY,
array(
'headers' => array(
'Content-Type' => 'text/xml; charset=UTF-8',
'SOAPAction' => 'HotelAvail',
),
'timeout' => 60,
),
$request_info
);
$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));
foreach ($response_xml->xpath('//#HotelName') as $HotelName) {
echo strval($HotelName) . "\n";
}
Note that in PHP 5.2 you'll need pecl_http, as far as (surprise-surpise!) there's no HTTP client built in.
Going to bare HTTP gained us over 30% in SOAP request times. And from then on we redirect all the performance complains to the server guys.
In the end, I'd recommend this latter approach, and not because of the performance. I think that, in general, in a dynamic language like PHP there's no benefit from all that WSDL/type-control. You don't need a fancy library to read and write XML, with all that stubs generation and dynamic proxies. Your language is already dynamic, and SimpleXMLElement works just fine, and is so easy to use. Also, you'll have less code, which is always good.
PHP has SOAP support.
Just call
$client = new SoapClient($url);
to connect to the SoapServer and then you can get list of functions and call functions simply by doing...
$client->__getTypes();
$client->__getFunctions();
$result = $client->functionName();
for more http://www.php.net/manual/en/soapclient.soapclient.php
I needed to do many very simple XML requests and after reading #Ivan Krechetov's comment about the speed hit of SOAP, I tried his code and discovered http_post_data() is not built into PHP 5.2. Not really wanting to install it, I tried cURL which is on all my servers. Although I do not know how fast cURL is compared to SOAP, it sure was easy to do what I needed. Below is a sample with cURL for anyone needing it.
$xml_data = '<?xml version="1.0" encoding="UTF-8" ?>
<priceRequest><customerNo>123</customerNo><password>abc</password><skuList><SKU>99999</SKU><lineNumber>1</lineNumber></skuList></priceRequest>';
$URL = "https://test.testserver.com/PriceAvailability";
$ch = curl_init($URL);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL.
Create the soap-server.php which write the SOAP request into soap-request.xml in web folder.
We can use the PHP cURL library to generate simple HTTP POST request. The following example shows you how to create a simple SOAP request using cURL.
Create the soap-server.php which write the SOAP request into soap-request.xml in web folder.
<?php
$HTTP_RAW_POST_DATA = isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : '';
$f = fopen("./soap-request.xml", "w");
fwrite($f, $HTTP_RAW_POST_DATA);
fclose($f);
?>
The next step is creating the soap-client.php which generate the SOAP request using the cURL library and send it to the soap-server.php URL.
<?php
$soap_request = "<?xml version=\"1.0\"?>\n";
$soap_request .= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n";
$soap_request .= " <soap:Body xmlns:m=\"http://www.example.org/stock\">\n";
$soap_request .= " <m:GetStockPrice>\n";
$soap_request .= " <m:StockName>IBM</m:StockName>\n";
$soap_request .= " </m:GetStockPrice>\n";
$soap_request .= " </soap:Body>\n";
$soap_request .= "</soap:Envelope>";
$header = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: \"run\"",
"Content-length: ".strlen($soap_request),
);
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, "http://localhost/php-soap-curl/soap-server.php" );
curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($soap_do, CURLOPT_TIMEOUT, 10);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($soap_do, CURLOPT_POST, true );
curl_setopt($soap_do, CURLOPT_POSTFIELDS, $soap_request);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
if(curl_exec($soap_do) === false) {
$err = 'Curl error: ' . curl_error($soap_do);
curl_close($soap_do);
print $err;
} else {
curl_close($soap_do);
print 'Operation completed without any errors';
}
?>
Enter the soap-client.php URL in browser to send the SOAP message. If success, Operation completed without any errors will be shown and the soap-request.xml will be created.
<?xml version="1.0"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2001/12/soap-envelope" soap:encodingStyle="http://www.w3.org/2001/12/soap-encoding">
<soap:Body xmlns:m="http://www.example.org/stock">
<m:GetStockPrice>
<m:StockName>IBM</m:StockName>
</m:GetStockPrice>
</soap:Body>
</soap:Envelope>
Original - http://eureka.ykyuen.info/2011/05/05/php-send-a-soap-request-by-curl/
You might want to look here and here.
A Little code example from the first link:
<?php
// include the SOAP classes
require_once('nusoap.php');
// define parameter array (ISBN number)
$param = array('isbn'=>'0385503954');
// define path to server application
$serverpath ='http://services.xmethods.net:80/soap/servlet/rpcrouter';
//define method namespace
$namespace="urn:xmethods-BNPriceCheck";
// create client object
$client = new soapclient($serverpath);
// make the call
$price = $client->call('getPrice',$param,$namespace);
// if a fault occurred, output error info
if (isset($fault)) {
print "Error: ". $fault;
}
else if ($price == -1) {
print "The book is not in the database.";
} else {
// otherwise output the result
print "The price of book number ". $param[isbn] ." is $". $price;
}
// kill object
unset($client);
?>
Below is a quick example of how to do this (which best explained the matter to me) that I essentially found at this website. That website link also explains WSDL, which is important for working with SOAP services.
However, I don't think the API address they were using in the example below still works, so just switch in one of your own choosing.
$wsdl = 'http://terraservice.net/TerraService.asmx?WSDL';
$trace = true;
$exceptions = false;
$xml_array['placeName'] = 'Pomona';
$xml_array['MaxItems'] = 3;
$xml_array['imagePresence'] = true;
$client = new SoapClient($wsdl, array('trace' => $trace, 'exceptions' => $exceptions));
$response = $client->GetPlaceList($xml_array);
var_dump($response);
If the XML have identities with same name in different levels there is a solution. You don´t have to ever submit a raw XML (this PHP SOAP object don´t allows send a RAW XML), so you have to always translate your XML to a array, like the example below:
$originalXML = "
<xml>
<firstClient>
<name>someone</name>
<adress>R. 1001</adress>
</firstClient>
<secondClient>
<name>another one</name>
<adress></adress>
</secondClient>
</xml>"
//Translate the XML above in a array, like PHP SOAP function requires
$myParams = array('firstClient' => array('name' => 'someone',
'adress' => 'R. 1001'),
'secondClient' => array('name' => 'another one',
'adress' => ''));
$webService = new SoapClient($someURL);
$result = $webService->someWebServiceFunction($myParams);
or
$soapUrl = "http://privpakservices.schenker.nu/package/package_1.3/packageservices.asmx?op=SearchCollectionPoint";
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?><soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope"><soap12:Body><SearchCollectionPoint xmlns="http://privpakservices.schenker.nu/"><customerID>XXX</customerID><key>XXXXXX-XXXXXX</key><serviceID></serviceID><paramID>0</paramID><address>RiksvŠgen 5</address><postcode>59018</postcode><city>Mantorp</city><maxhits>10</maxhits></SearchCollectionPoint></soap12:Body></soap12:Envelope>';
$headers = array(
"POST /package/package_1.3/packageservices.asmx HTTP/1.1",
"Host: privpakservices.schenker.nu",
"Content-Type: application/soap+xml; charset=utf-8",
"Content-Length: ".strlen($xml_post_string)
);
$url = $soapUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
$parser = simplexml_load_string($response2);

Categories