How to add an arbitrary namespace with PHP SoapClient? - php

How does one add an arbitrary namespace using PHP SoapClient? The namespace does not actually get used in the request, but I think it is preventing my message from being properly consumed.
The WSDL is here : http://abr.business.gov.au/abrxmlsearchRPC/ABRXMLSearch.asmx?WSDL
The documentation for the particular message I want to send is here : http://abr.business.gov.au/abrxmlsearchRPC/(nye2ok45xc42vy552b15dx3t)/FormGenerator/ABRSearchByNameSimpleProtocol.aspx. I'm doing the SOAP request.
In the soap:Envelope, you'll notice a namespace called xmlns:types="http://abr.business.gov.au/ABRXMLSearchRPC/encodedTypes", and you'll also notice it's not used in the soap:Body.
The message I'm sending is : (newlines and indenting added for readability, authenticationGuid obfuscated for security)
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://abr.business.gov.au/ABRXMLSearchRPC/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAP-ENV:Body>
<ns1:ABRSearchByNameSimpleProtocol>
<name xsi:type="xsd:string">company</name>
<postcode xsi:type="xsd:string"></postcode>
<legalName xsi:type="xsd:string">Y</legalName>
<tradingName xsi:type="xsd:string">Y</tradingName>
<NSW xsi:type="xsd:string">Y</NSW>
<SA xsi:type="xsd:string">Y</SA>
<ACT xsi:type="xsd:string">Y</ACT>
<VIC xsi:type="xsd:string">Y</VIC>
<WA xsi:type="xsd:string">Y</WA>
<NT xsi:type="xsd:string">Y</NT>
<QLD xsi:type="xsd:string">Y</QLD>
<TAS xsi:type="xsd:string">Y</TAS>
<authenticationGuid xsi:type="xsd:string">aaaa</authenticationGuid>
</ns1:ABRSearchByNameSimpleProtocol>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
The response I get back is :
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:tns="http://abr.business.gov.au/ABRXMLSearchRPC/" xmlns:types="http://abr.business.gov.au/ABRXMLSearchRPC/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Body soap:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<types:ABRSearchByNameSimpleProtocolResponse><ABRSearchByNameSimpleProtocolResult href="#id1" /></types:ABRSearchByNameSimpleProtocolResponse>
<types:Payload id="id1" xsi:type="types:Payload">
<Request href="#id2" />
<Response href="#id3" />
</types:Payload>
<types:ExternalRequest id="id2" xsi:type="types:ExternalRequest">
<ExternalRequestBody href="#id4" />
</types:ExternalRequest>
<types:Response id="id3" xsi:type="types:Response">
<DateRegisterLastUpdated xsi:type="xsd:dateTime">0001-01-01T00:00:00.0000000+11:00</DateRegisterLastUpdated>
<DateTimeRetrieved xsi:type="xsd:dateTime">2011-05-26T09:31:06.2949724+10:00</DateTimeRetrieved>
<ResponseBody href="#id5" />
</types:Response>
<types:ExternalRequestNameSearch id="id4" xsi:type="types:ExternalRequestNameSearch">
<AuthenticationGUID xsi:type="xsd:string" />
<Name xsi:type="xsd:string" />
<Filters href="#id6" />
</types:ExternalRequestNameSearch>
<types:ResponseException id="id5" xsi:type="types:ResponseException">
<ExceptionDescription xsi:type="xsd:string">The GUID entered is not recognised as a Registered Party.
Search GUID: </ExceptionDescription>
<ExceptionCode xsi:type="xsd:string">WebServices</ExceptionCode>
</types:ResponseException>
<types:ExternalRequestFilters id="id6" xsi:type="types:ExternalRequestFilters">
<NameType href="#id7" />
<Postcode xsi:type="xsd:string" />
<StateCode href="#id8" />
</types:ExternalRequestFilters>
<types:ExternalRequestFilterNameType id="id7" xsi:type="types:ExternalRequestFilterNameType">
<TradingName xsi:type="xsd:string">Y</TradingName>
<LegalName xsi:type="xsd:string">Y</LegalName>
</types:ExternalRequestFilterNameType>
<types:ExternalRequestFilterStateCode id="id8" xsi:type="types:ExternalRequestFilterStateCode">
<QLD xsi:type="xsd:string">Y</QLD>
<NT xsi:type="xsd:string">Y</NT>
<SA xsi:type="xsd:string">Y</SA>
<WA xsi:type="xsd:string">Y</WA>
<VIC xsi:type="xsd:string">Y</VIC>
<ACT xsi:type="xsd:string">Y</ACT>
<TAS xsi:type="xsd:string">Y</TAS>
<NSW xsi:type="xsd:string">Y</NSW>
</types:ExternalRequestFilterStateCode>
</soap:Body>
</soap:Envelope>
It looks like the consumer has completely disregarded the content of the message. The only thing I can see that is missing from the example is the types namespace, which is included in the response.
Thus, I'm thinking that if I can arbitrarily add the types namespace to the request, it may have better luck.
If anyone could tell me how to do that, or offer some other suggestion why the consumer ignores the values I've given in the request, that would be greatly appreciated.
Update: Extending SoapClient and overriding __doRequest() to add the namespace might actually be the solution, but I'd like a confirmation from someone who knows better. It should be noted that the content of SoapClient::getLastRequest() is generated before modifications made by __doRequest(), so any modifications made via __doRequest() may need to be observed via a tcp dump.
Example code for this is
class ABRSoapClient extends SoapClient {
function __doRequest($request, $location, $action, $version) {
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->preserveWhiteSpace = false;
$dom->loadXML($request);
$dom->documentElement->setAttribute
('xmlns:types', 'http://abr.business.gov.au/ABRXMLSearchRPC/encodedTypes');
$request = $dom->saveXML();
error_log('Request in class:'.$request);
return parent::__doRequest($request, $location, $action, $version);
}
}

Related

PHP - SOAP request - nest xml as param?

I need to make the structure of my XML SOAP request to look like following:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.fines.pl/api/contract">
<SOAP-ENV:Body>
<ns1:newApplicationRequest>
<user_login>XYZ</user_login>
<user_password>XYZ</user_password>
<contract>
<?xml version="1.0" encoding="UTF-8"?>
<sof:Contract xmlns:s="http://www.fines.pl/simple" xmlns:sof="http://www.fines.pl/sof" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.fines.pl/sof model.xsd ">
<product>
<prefix>MOP</prefix>
</product>
<participants>
<customers>
<main_borrower>
<personal_data>
<pesel>85050949761</pesel>
<firstname>Anna</firstname>
<lastname>Test</lastname>
<firstname_father></firstname_father>
<firstname_mother></firstname_mother>
<secondname />
<sex>female</sex>
</personal_data>
<contact_data>
<addresses>
<address>
<type>registered</type>
<street_name>Grunwaldzka</street_name>
<block_number>11</block_number>
<flat_number>5</flat_number>
<postal_code>80-100</postal_code>
<city>GdaƄsk</city>
</address>
</addresses>
<phones_mobile>
<phone_mobile>
<type>personal</type>
<number>602200300</number>
</phone_mobile>
</phones_mobile>
</contact_data>
<incomes>
<income>
<type>employment</type>
<main_income>true</main_income>
<fixed_term_contract>false</fixed_term_contract>
<paychecks>
<paycheck>
<amount_net>
<amount>1444.00</amount>
<currency>PLN</currency>
</amount_net>
<type>base</type>
</paycheck>
</paychecks>
</income>
</incomes>
<household_pointer>/households.0</household_pointer>
</main_borrower>
</customers>
</participants>
</sof:Contract></contract></ns1:newApplicationRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>
I've set my $params variable to contain user_login and user_password elements with their respective values, but I have no idea how may I set this contract param with required content.
Providing $contract variable with XML code (which i thought may be a workaround) poop the Fatal error: Uncaught SoapFault exception: [xml_structure] String could not be parsed as XML error.
Would be grateful for explaining how could this be done.
You have declared <?xml?> twice , one on the first line and second on the eight. That's the only error I see in the xml side of things.

SOAP response to PHP Array, reaching node Attributes

I'm trying to convert the following response into an array in PHP, I want to reach the data inside 'Timbre', I need the values of:
UUID
FechaTimbrado
SelloSAT
The solutions I've tried around here convert the nodes ok, but I can't find a way to reach nothing beyond 'Timbre', hope you can help me find a way to do this, here's the response I'm receiving:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<soap:Header>
<ResponseHeader trackId="119588" RequestDateTime="2017-11-09T11:55:39.0205969-06:00" IPCaller="187.190.165.93" ClienteId="0" Estatus="1" ID="91a407fe-c1c2-40af-bc2d-5aee58606161" Detail="" Ambiente="DESARROLLO-01" xmlns="https://cfdi.timbrado.com.mx/timbradov2">
<CFDI Id="CFDI33" FechaHora="2017-11-09T11:45:30" RFCEmisor="XXXHHK2343434" RFCReceptor="GFGDS45&667" Serie="G" Folio="35010" />
</ResponseHeader>
</soap:Header>
<soap:Body>
<GeneraTimbreResponse xmlns="https://cfdi.timbrado.com.mx/timbradov2">
<GeneraTimbreResult>
<Timbre>
<tfd:TimbreFiscalDigital xmlns:tfd="http://www.sat.gob.mx/TimbreFiscalDigital" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sat.gob.mx/TimbreFiscalDigital http://www.sat.gob.mx/sitio_internet/cfd/TimbreFiscalDigital/TimbreFiscalDigitalv11.xsd" Version="1.1" UUID="91A407FE-C1C2-40AF-BC2D-5AEE58606161" FechaTimbrado="2017-11-09T11:55:39" RfcProvCertif="ASE0209252Q1" Leyenda="Timbre de prueba" SelloCFD="WCldH0Oan7h2VK3MuMM3Nv8HAg/OlCaKF2VLz/1u81yvZItgZuYia1Aaz27hOYsqBZ/m5/OhAaL6TZ43MZSF6zK9tZz+Fgu9wS2QJ+ubk/83oIjQDwLHCuJL/l5VRZI29RoPUfs3VDb+tD9mqeEinQwfLJG1YkoCIWC/4oXxL1oX5DEXqMW/sK52jpJh7exyqw+GzBA+LUBaSi+aGHlown8cEQmZOZieeUW5uXjDPQBdJBZ/XkRgfqzAiS/Tfj9a61B0Nrm7JyejagPZVW7E3gbcmFunWTbGwNEYvqWkgtnO7aoTzrVcjK3YX4t2zKPt8F7BGq+MSL/fge174IttGQ==" NoCertificadoSAT="20001000000300022323" SelloSAT="NhzPGgUh+1vQJkidObRpp+IgjSdOm6wwgMVVcPdEVmVEbFgCBW42a7grzg8toe9d/ZlHhka5g6h63E5jp3xKcq2KnWw+dQbrbh8xDNHC+7tPXEJN9T5JU8ZifpvTIu9g89TYERUs/4sLgAYtqAmV9AIQK17LoAIiNRdUzwWiiHUCLaqL7k0bmJYvfeuYAnkw52LfyxzLDg6TyodT/1LjJVwhGLyaOcOwCDObHH8ukZj0d2aOwOEE0IJBbbIgh3VaIp0/EvvFn1I1F9BnrLHVZFEcR3ZeP/TyLJmuOtxLGDnPtnaVQTrt0sQb43bG2R2ut5Bt3uS12xOMx3IfDr/3FQ==" />
</Timbre>
</GeneraTimbreResult>
</GeneraTimbreResponse>
</soap:Body>
</soap:Envelope>
So I solved it like this, if anyone knows a 'classier' way , let me know
//here I read the result string I posted above
$soap = simplexml_load_string(html_entity_decode($this->resultado_timbre));
//I read the nodes until I reach the 'Timbre' one
$response = $soap->children('http://www.w3.org/2003/05/soap-envelope')->Body->children()->children()->children()->Timbre->children('tfd',TRUE);
//The attributes are readable in a nice array
$atributos=$response->attributes();
Hope it helps someone!

PHP - SOAP xml returning empty when SimpleXmlElement object created

I've been trying to figure this out for over an hour now, and I give up. I'm getting the following response from a webservice.
I want to be able to get access to the children of Fault (I have this working for another webservice call, but for some reason, which I believe MIGHT be namespace related, this one doesn't work).
<soap:envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Invalid Scope</faultstring>
<detail>
<faultresponse xmlns="xsd url" xmlns:ns2="xsd url">
<transactionid>TEST</transactionid>
<errorcode>ERR-4223</errorcode>
</faultresponse>
</detail>
</soap:Fault>
</soap:Body>
</soap:envelope>
My PHP code is pretty simple. Firstly, I create the SimpleXmlElement object from the above xml.
I get a list of namespaces in the xml (which it picks up two: "soap", and ""). I then get the children of the XML in the soap: namespace.
$xml = simplexml_load_string($response_xml);
$namespace = $xml->getNamespaces(true);
$soap = $xml->children($namespace['soap']);
Given the above code. I would expect to be able to do something like this:
$fault_fields = $soap->Body->children()->Fault->children();
foreach ($fault_fields as $field):
echo (string) $field->getName() . ' - ' . $field[0] . '<br />';
endforeach;
However, if I run $soap->asXML(); I can see the following:
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Invalid Scope</faultstring>
<detail>
<faultresponse xmlns="xsd url" xmlns:ns2="xsd url">
<transactionid>TEST</transactionid>
<errorcode>ERR-4223</errorcode>
</faultresponse>
</detail>
</soap:Fault>
</soap:Body>
But if I try to go to access Body or Fault:
$soap = &$this->parse_soap_body($response_xml);
$body = $soap->Body->children()->Fault->children();
echo $body->asXML();
I get a Node no longer exists error with the stack returning this XML.
<soap:Envelope xmlns:soap="`http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<soap:Fault>
<faultcode>soap:Server</faultcode>
<faultstring>Invalid Scope</faultstring>
.... more xml
This is seriously doing my head in.
Any help would be greatly appreciated.

Parsing SOAP response with PHP

SO,
I'm receiving the following SOAP response as a string:
<?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:Body>
<GetListItemsResponse xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<GetListItemsResult>
<listitems xmlns:s="uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882" xmlns:dt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882" xmlns:rs="urn:schemas-microsoft-com:rowset" xmlns:z="#RowsetSchema">
<rs:data ItemCount="3">
<z:row ows_DocIcon="jpg" ows_LinkFilename="18380014229851.jpg" ows_Modified="2016-10-08 17:27:40" ows_Editor="179440;#asdf" ows_Last_x0020_Modified="2;#2016-10-08 17:29:29" ows_ID="2" ows_Created_x0020_Date="2;#2016-10-08 17:27:40" ows_FileLeafRef="2;#18380014229851.jpg" />
<z:row ows_DocIcon="jpg" ows_LinkFilename="18380014229851_2.jpg" ows_Modified="2016-10-08 17:27:40" ows_Editor="179440;#asfd" ows_Last_x0020_Modified="3;#2016-10-08 17:29:29" ows_ID="3" ows_Created_x0020_Date="3;#2016-10-08 17:27:41" ows_FileLeafRef="3;#18380014229851_2.jpg" />
<z:row ows_DocIcon="jpg" ows_LinkFilename="18380014229851_3.jpg" ows_Modified="2016-10-08 17:27:40" ows_Editor="179440;#asdf" ows_Last_x0020_Modified="4;#2016-10-08 17:30:03" ows_ID="4" ows_Created_x0020_Date="4;#2016-10-08 17:27:41" ows_FileLeafRef="4;#18380014229851_3.jpg" />
</rs:data>
</listitems>
</GetListItemsResult>
</GetListItemsResponse>
</soap:Body>
</soap:Envelope>
I am attempting to get each of the "z:row" entries, but am struggling due to the namespaces (after some googling that's what i'm understanding them to be called).
Here is the code I am using:
$xml = simplexml_load_string($sp->soapClient->__last_response);
foreach($xml->GetListItemsResult as $item)
{
$ns_li = $item->children('uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882');
$ns_rs = $ns_li->children('urn:schemas-microsoft-com:rowset');
$ns_z = $nr_rs->children('#RowsetSchema');
echo $ns_z->row;
}
Right now I am getting no output from echo statement. What am I doing wrong?
You can use XPath expression to get specific part of XML document using various criteria. For example, to get z:row elements anywhere in the XML document you can simply do //z:row, after registering the prefix z :
$xml->registerXPathNamespace("z", "#RowsetSchema");
foreach($xml->xpath('//z:row') as $item)
{
echo $item["ows_LinkFilename"] ."\n";
}
eval.in demo
output :
18380014229851.jpg
18380014229851_2.jpg
18380014229851_3.jpg

SoapClient XML return string with simpleXML

So I'm getting an xml file back from a soap service (of which I have no control over). It's returning back an xmlns which is causing simpleXML issues. I'm running a str_replace to get rid of that issue, however now simpleXML just returns an empty object. XML structure appears to be fine, no errors just an empty object.
$xmlString = $client->__getLastResponse();
$feed = str_replace(' xmlns="LMSWebservice"', '', $xmlString);
$sData= simplexml_load_string($feed);
print_r($sData);
Returns: SimpleXMLElement Object()
XML source before str replace is:
<?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:Body>
<GetUserInternalIDByPersonalIDResponse xmlns="LMSWebservice">
<GetUserInternalIDByPersonalIDResult>
<Response xmlns="">
<Timestamp date="24/10/2013" time="04:27:37" />
<User>
<UserInternalID>4907</UserInternalID>
</User>
</Response>
</GetUserInternalIDByPersonalIDResult>
</GetUserInternalIDByPersonalIDResponse>
</soap:Body>
</soap:Envelope>
After str replace:
<?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:Body>
<GetUserInternalIDByPersonalIDResponse>
<GetUserInternalIDByPersonalIDResult>
<Response xmlns="">
<Timestamp date="24/10/2013" time="04:27:37" />
<User>
<UserInternalID>4907</UserInternalID>
</User>
</Response>
</GetUserInternalIDByPersonalIDResult>
</GetUserInternalIDByPersonalIDResponse>
</soap:Body>
</soap:Envelope>
Any help would be greatly appreciated, this is driving me crazy!
----So if I don't get rid of the namespace attribute I get this error message:
Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser warning : xmlns: URI LMSWebservice is not absolute in serviceTest2.php on line 16
Warning: simplexml_load_string() [function.simplexml-load-string]: LSchema"><soap:Body><GetUserInternalIDByPersonalIDResponse xmlns="LMSWebservice" in serviceTest2.php on line 16
Warning: simplexml_load_string() [function.simplexml-load-string]: ^ in serviceTest2.php on line 16
If I try using xPath to get at UserInternalID it returns an empty array. If what you're saying is correct and this is going into simpleXML correctly, then how do I access the UserInternalID node? Sorry, this is the first time using simpleXML and this is just perplexing me.
So just tried changing the NS
$feed = str_replace('xmlns="LMSWebservice"', 'xmlns="ns:LMSWebservice"', $xmlString);
which goes in without errors.
I tried this for the xPath
$ID = $sData->xpath('UserInternalID');
I understand this is probably completely wrong, but I haven't tried much else with this as it didn't seem to be going into simpleXML correctly in the first place. :/
So I've used
$ID = $sData->xpath('//UserInternalID');
echo $ID[0];
Which works perfectly. Thank you for all your help!
Through the extensive comments and your last edit finally the actual cause of your problem could be revealed, the xpath expression is wrong:
$ID = $sData->xpath('UserInternalID');
Wrong with it is the path, this matches no elements. Instead you could use:
$ID = (string) $xml->xpath('//UserInternalID')[0];
Or more verbose:
$ID = (string) $xml->xpath('//Response/User/UserInternalID')[0];
Key point here is that you write the correct path to the element you would like to query for.
Complete usage example:
<?php
/**
* SoapClient xml return string with simpleXML
*
* #link http://stackoverflow.com/q/19556414/367456
*/
$response = <<<RESPONSE
<?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:Body>
<GetUserInternalIDByPersonalIDResponse xmlns="LMSWebservice">
<GetUserInternalIDByPersonalIDResult>
<Response xmlns="">
<Timestamp date="24/10/2013" time="04:27:37" />
<User>
<UserInternalID>4907</UserInternalID>
</User>
</Response>
</GetUserInternalIDByPersonalIDResult>
</GetUserInternalIDByPersonalIDResponse>
</soap:Body>
</soap:Envelope>
RESPONSE;
$restore = libxml_use_internal_errors(TRUE);
$xml = simplexml_load_string($response);
libxml_use_internal_errors($restore);
echo $xml->xpath('//Response/User/UserInternalID')[0];
Output:
4907
Online Demo: https://eval.in/57149
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($response);
libxml_clear_errors();
$xml = $doc->saveXML($doc->documentElement);
$xml = simplexml_load_string($xml);
Use this helped me in a big way.

Categories