SOAP parsing in PHP - php

I created a SOAP client in PHP:
$client = new SoapClient("http://xxxx.net/Service/Service.svc?wsdl");
$response= $client->GetHotelNugget($data);
But I can't parse the response. I need <a:TITLE> tag value.
Output of the SOAP client:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetHotelNuggetResponse xmlns="http://tempuri.org/">
<GetHotelNuggetResult xmlns:a="http://schemas.datacontract.org/2004/07/Model" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:HotelNugget>
<a:NUGGETNAME>Yaz Tatili Otelleri</a:NUGGETNAME>
<a:NUGGETORDER>10</a:NUGGETORDER>
<a:PARENTUNIQUECODE>AS_SOL_UST</a:PARENTUNIQUECODE>
<a:REWRITENUGGETNAME>yaz-tatili-otelleri</a:REWRITENUGGETNAME>
<a:TITLE>Yaz Tatili Otelleri</a:TITLE>
<a:UNIQUECODE>YTOTL</a:UNIQUECODE>
<a:WEBNUGGETID>306</a:WEBNUGGETID>
</a:HotelNugget>
<a:HotelNugget>
<a:NUGGETNAME>Ramazan Fırsatları</a:NUGGETNAME>
<a:NUGGETORDER>20</a:NUGGETORDER>
<a:PARENTUNIQUECODE>AS_SOL_UST</a:PARENTUNIQUECODE>
<a:REWRITENUGGETNAME>ramazan-firsatlari</a:REWRITENUGGETNAME>
<a:TITLE>Ramazan Fırsatları</a:TITLE>
<a:UNIQUECODE>RFIR</a:UNIQUECODE>
<a:WEBNUGGETID>308</a:WEBNUGGETID>
</a:HotelNugget>
<a:HotelNugget>
<a:NUGGETNAME>Ramazan Bayramı Otelleri</a:NUGGETNAME>
<a:NUGGETORDER>30</a:NUGGETORDER>
<a:PARENTUNIQUECODE>AS_SOL_UST</a:PARENTUNIQUECODE>
<a:REWRITENUGGETNAME>ramazan-bayrami-otelleri</a:REWRITENUGGETNAME>
<a:TITLE>Ramazan Bayramı Otelleri</a:TITLE>
<a:UNIQUECODE>RBO</a:UNIQUECODE>
<a:WEBNUGGETID>283</a:WEBNUGGETID>
</a:HotelNugget>
</GetHotelNuggetResult>
</GetHotelNuggetResponse>
</s:Body>
</s:Envelope>

Try below code and check the print_r value
$xmlResp = simplexml_load_string($response);
$jsonResp = json_encode($xmlResp);
$arrResp = json_decode($jsonResp);
foreach($arrResp as $k=>$v) {
print_r($v);
}
You can then access the TITLE tag inside foreach by something like below
$v['HotelNugget']['TITLE'];

Related

guzzle xml request returns only plain text

im trying to make a xml request to a ws using guzzle,(and i try with curl to) in php but always the response its in plain text no in xml
$client = new \GuzzleHttp\Client(['verify' => false]);
$soapRequest = <<<XML
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:tem="http://tempuri.org/" xmlns:san="mywebsservice">
<soap:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:Action>http://tempuri.org/mywebsservice</wsa:Action>
<To soap:mustUnderstand="1" xmlns="http://www.w3.org/2005/08/addressing">mywebsservice </To>
</soap:Header>
<soap:Body>
<tem:GetSecurityToken>
<tem:request>
<san:Connection>mywebsservice</san:Connection>
<san:Passwoord>mywebsservice</san:Passwoord>
<san:System>mywebsservice</san:System>
<san:UserName>mywebsservice</san:UserName>
</tem:request>
</tem:GetSecurityToken>
</soap:Body>
</soap:Envelope>
XML;
$request = $client->request('POST','mywebsservice', [
'headers' => [
'Content-Type' => 'application/soap+xml'
],
'body' => $soapRequest
]);
$response = $request->getBody()->getContents();
var_dump($response);
this is the response
this is the response
string(1870) "
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">
<s:Header>
<a:Action s:mustUnderstand="1">http://tempuri.org/webservices/GetSecurityTokenResponse</a:Action>
<ActivityId CorrelationId="cf1c12da-af1b-4013-ba89-25db2fa67dc1" xmlns="http://schemas.microsoft.com/2004/09/ServiceModel/Diagnostics">00000000-0000-0000-0000-000000000000</ActivityId>
</s:Header>
<s:Body>
<GetSecurityTokenResponse xmlns="http://tempuri.org/">
<GetSecurityTokenResult xmlns:b="webservices" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<b:AccessToken>token access</b:AccessToken>
<b:IdToken>the token</b:IdToken>
<b:TokenType>Bearer</b:TokenType>
</GetSecurityTokenResult>
</GetSecurityTokenResponse>
</s:Body>
</s:Envelope>
"
The headers you are sending is what the receiving server uses to decide what content to serve. It will still be text content though, but only with a different Content-Type header.
guzzlehttp/guzzle 6.x
The $response->json() and $response->xml() helpers were removed in 6.x. The following lines can be used to replicate that behaviour:
// Get an associative array from a JSON response.
$data = json_decode($response->getBody(), true);
See https://www.php.net/manual/en/function.json-decode.php
// Get a `SimpleXMLElement` object from an XML response.
$xml = simplexml_load_string($response->getBody());
See https://www.php.net/manual/en/function.simplexml-load-string.php
guzzlehttp/guzzle 5.x
Guzzle 5.x has some shortcuts to help you out:
$client = new Client(['base_uri' => 'https://example.com']);
$response = $client->get('/');
// $response = Psr\Http\Message\ResponseInterface
$body = (string) $response->getBody();
// $body = raw request contents in string format.
// If you dont cast `(string)`, you'll get a Stream object which is another story.
Now whatever you do with $body is up to you. If it is a JSON response, you'd do:
$data = $response->json();
If it is XML, you can call:
$xml = $response->xml();
I never work with XML APIs so i can't give you any more examples on how to traverse the XML you will retrieve.

SOAP with literal xml in php

How do i create this specific xml output by SOAP using SoapHeader and __setSoapHeaders? I can't do the same XML like i want. i don't want this ns1 and ns2 in envelope tag, and in header i need this Action SOAP-ENV:mustUnderstand="1" ...
This is my code:
try{
$client = new SoapClient('https://thesite.com.br/wcf/SvcContratos.svc?wsdl', array('trace' => 1,'use' => SOAP_LITERAL));
$usuario='user_1';
$senha='1234';
$tipo='1';
$header = new SoapHeader("http://schemas.microsoft.com/ws/2005/05/addressing/none","Action", "http://tempuri.org/ISvcContratos/GerarToken");
$client->__setSoapHeaders($header);
$params = new SoapVar("<objLogin xmlns:d4p1='http://schemas.datacontract.org/2004/07/EPFWeb.Repository.Default.WCF' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><d4p1:DsSenha>".$senha."</d4p1:DsSenha><d4p1:DsUsuario>".$usuario."</d4p1:DsUsuario><d4p1:IdTipoConsulta>".$tipo."</d4p1:IdTipoConsulta></objLogin>", XSD_ANYXML);
$data = $client->GerarToken($params);
echo $client->__getLastRequest();
}catch(SoapFault $fault){
echo $client->__getLastRequest()."<br>".$fault->getMessage();
}
With this php code i had this wrong XML:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/" xmlns:ns2="http://schemas.microsoft.com/ws/2005/05/addressing/none">
<SOAP-ENV:Header>
<ns2:Action>http://tempuri.org/ISvcContratos/GerarToken</ns2:Action>
</SOAP-ENV:Header>
<SOAP-ENV:Body>
<GerarToken>
<objLogin xmlns:d4p1='http://schemas.datacontract.org/2004/07/EPFWeb.Repository.Default.WCF' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'>
<d4p1:DsSenha>1234</d4p1:DsSenha>
<d4p1:DsUsuario>user_1</d4p1:DsUsuario>
<d4p1:IdTipoConsulta>1</d4p1:IdTipoConsulta>
</objLogin>
</GerarToken>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
I need to send this XML by soap:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">http://tempuri.org/ISvcContratos/GerarToken</Action>
</s:Header>
<s:Body>
<GerarToken xmlns="http://tempuri.org/">
<objLogin xmlns:d4p1="http://schemas.datacontract.org/2004/07/EPFWeb.Repository.Default.WCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<d4p1:DsSenha>1234</d4p1:DsSenha>
<d4p1:DsUsuario>USER_1</d4p1:DsUsuario>
<d4p1:IdTipoConsulta>1</d4p1:IdTipoConsulta>
</objLogin>
</GerarToken>
</s:Body>
</s:Envelope>
well, finally I got an affirmative answer from the server, which opens the doors for me now to try to consume the wsdl follows below the code that I used to solve the problem:
try{
$client = new SoapClient('https://thesite.com.br/wcf/SvcContratos.svc?wsdl', array('trace' => 1,'use' => SOAP_LITERAL, 'style' => SOAP_DOCUMENT,));
$usuario='user_1';
$senha='1234';
$params = new SoapVar("<GerarToken xmlns='http://tempuri.org/'><objLogin xmlns:d4p1='http://schemas.datacontract.org/2004/07/EPFWeb.Repository.Default.WCF' xmlns:i='http://www.w3.org/2001/XMLSchema-instance'><d4p1:DsUsuario>".$usuario."</d4p1:DsUsuario><d4p1:DsSenha>".$senha."</d4p1:DsSenha><d4p1:IdTipoConsulta>Data</d4p1:IdTipoConsulta></objLogin></GerarToken>", XSD_ANYXML);
$data = $client->GerarToken($params);
$xml = json_decode(json_encode($data),true);
print_r($xml);
echo $client->__getLastRequest();
}catch(SoapFault $fault){
echo $client->__getLastRequest()."<br>".$fault->getMessage();
}

how to extract SOAP response in PHP

I have a SOAP response as follows:
<?xml version="1.0" ?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault xmlns:ns4="http://www.w3.org/2003/05/soap-envelope" xmlns="">
<faultcode>stuff</faultcode>
<faultstring>stuff</faultstring>
<detail>
<ns2:Exception xmlns:ns2="http://blah.com/">
<message>stuff</message>
</ns2:Exception>
</detail>
</S:Fault>
</S:Body>
</S:Envelope>
I need to extract faultcode, faultstring, and message.
I have tried SimpleXML_load_string, SimpleXMLElement, DOMDocument, registerXPathNamespace and json_decode but can't seem to get the exact procedure correct because I get errors instead of results. Thanks in advance.
Latest attempt:
$xmle1 = SimpleXML_load_string(curl_exec($ch));
if (curl_errno($ch)) {
print "curl error: [" . curl_error($ch) . "]";
} else {
$xmle1->registerXPathNamespace('thing1', 'http://blah.com/');
foreach ($xml->xpath('//thing1:message') as $item) {
echo (string) $item;
}
<?php
$string = <<<XML
<?xml version="1.0" ?>
<S:Envelope
xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
<S:Body>
<S:Fault
xmlns:ns4="http://www.w3.org/2003/05/soap-envelope"
xmlns="">
<faultcode>stuff</faultcode>
<faultstring>stuff</faultstring>
<detail>
<ns2:Exception
xmlns:ns2="http://blah.com/">
<message>stuff</message>
</ns2:Exception>
</detail>
</S:Fault>
</S:Body>
</S:Envelope>
XML;
$_DomObject = new DOMDocument;
$_DomObject->loadXML($string);
if (!$_DomObject) {
echo 'Error while parsing the document';
exit;
}
$s = simplexml_import_dom($_DomObject);
foreach(['faultcode','faultstring','message'] as $tag){
echo $tag.' => '.$_DomObject->getElementsByTagName($tag)[0]->textContent.'<br/>';
}
?>
outputs
faultcode => stuff
faultstring => stuff
message => stuff
you might want to write a class to parse the XML string and build an nice Fault object with methods for easier access after you parse it.

SOAP response - parsing xml in php, how to access?

I have response from webservice:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://tempuri.org/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<SOAP-ENV:Body>
<ns1:H1 xsi:type="ns1:H1">
<BOGUS>
<time>1411967345</time>
<status>1</status>
<speed>0</speed>
</BOGUS>
<BOGUS>
<time>1411964888</time>
<status>10</status>
<speed>0</speed>
</BOGUS>
</ns1:H1>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
How can I access to element time or status in BOGUS[0] or BOGUS[1]?
I tried this:
$soap = simplexml_load_string($str);
$response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://tempuri.org/')->H1;
$time = $response->BOGUS[1]->time;
echo $time;
, but it's not working. Returns: Notice: Trying to get property of non-object
tempuri.org is right. I pasted xml response on: xmlgrid.net and got correct tree.
I'd recommandate to use Zend Soap Client for PHP. There u can do like this:
$client = new Zend_Soap_Client("MyService.wsdl");
$result = $client->yourMethod(<YouParameters ...>);
echo $result->H1->BOGUS[1]->time;
See:
http://framework.zend.com/manual/1.12/de/zend.soap.client.html
You can do it by loops as you are getting array in return
foreach ($response as $res)
{
$time = $res->BOGUS[1]->time;
echo $time;
}

Trouble Parsing SOAP response in PHP using simplexml

I'm using cURL to POST a SOAP request. The response is as follows:
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:To>http://www.w3.org/2005/08/addressing/anonymous</wsa:To>
<wsa:Action>http://www.csapi.org/schema/parlayx/common/v3_1/TerminalLocationPort/getLocationForGroupResponse</wsa:Action>
</env:Header>
<env:Body>
<ns2:getLocationForGroupResponse xmlns:ns2="http://www.csapi.org/schema/parlayx/terminal_location/v3_1/local">
<ns2:result>
<address>234983</address>
<reportStatus>Retrieved</reportStatus>
<currentLocation>
<latitude>12.5665</latitude>
<longitude>43.7708</longitude>
<timestamp>2012-01-03T17:06:16.805+01:30</timestamp>
</currentLocation>
</ns2:result>
<ns2:result>
<address>423903</address>
<reportStatus>Retrieved</reportStatus>
<currentLocation>
<latitude>12.2165</latitude>
<longitude>43.6518</longitude>
<timestamp>2012-01-03T17:06:16.824+01:30</timestamp>
</currentLocation>
</ns2:result>
</ns2:getLocationForGroupResponse>
</env:Body>
</env:Envelope>
I use this to decode:
$err = curl_error($soap_do);
$result = curl_exec($soap_do);
$xml = simplexml_load_string($result);
$ns = $xml->getNamespaces(true);
$soap = $xml->children($ns['env']);
$getaddressresponse = $soap->body->children($ns['ns2']);
foreach ($getaddressresponse->children() as $item) {
echo (string) $item->address . '<br />';
}
I'm having trouble decoding this with SimpleXML. This link seems most relevant to my situation but I'm unable to apply it to my case as the simpleXML element just
Warning: SimpleXMLElement::children() [simplexmlelement.children]: Node no longer exists in C:\.php on line 33 /*(line with the for each statement)*/
Any suggestions?
UPDATE:
If the server responds with the following error, how would I detect it..?
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header xmlns:wsa="http://www.w3.org/2005/08/addressing">
<wsa:To>http://www.w3.org/2005/08/addressing/anonymous</wsa:To>
<wsa:Action>http://www.w3.org/2005/08/addressing/fault</wsa:Action>
</env:Header>
<env:Body>
<env:Fault>
<faultcode>env:Server</faultcode>
<faultstring>Service Exception</faultstring>
<detail>
<ns1:ServiceException xmlns:ns1="http://www.csapi.org/schema/parlayx/common/v3_1" xmlns:ns2="http://www.csapi.org/schema/parlayx/terminal_location/v3_1/local">
<messageId>SVC004</messageId>
<text>Trip not Found for this MSISDN</text>
</ns1:ServiceException>
</detail>
</env:Fault>
</env:Body>
</env:Envelope>
Variable and property names are case sensitive and while I was testing it, it turned out there's other stuff as well. The following works:
$soap = $xml->children($ns['env']);
$getaddressresponse = $soap->Body->children($ns['ns2']);
foreach ($getaddressresponse->getLocationForGroupResponse->children($ns['ns2']) as $item)
{
$item = $item->children();
echo $item->address . '<br />';
}
To answer the updated question:
$fault = $soap->Body->children($ns['env']);
if (isset($fault->Fault))
{
// Handle error
}

Categories