After hours of searching, finding similar threads and still not being able to get it to work I've resorted to posting my specific problem. I'm getting a SOAP encoded XML response from a server that i want to use SimpleXMLElement() on, but i'm having a real hard time establishing a base path to work from.
I've tried two different methods:
xpath():
public function XMLParseUserData($xml)
{
$ActivityData = new SimpleXMLElement($xml);
$ActivityData->registerXPathNamespace("ns", "http://webservices.website.net/");
$basePath = $ActivityData->xpath('//ns:GetUserActivityDataResult/ActArray');
foreach ($basePath->ACT as $userActivity)
{
$this->uGUID = $userActivity->UserGUID;
echo $this->uGUID."<br />";
}
}
children():
public function XMLParseUserData($xml)
{
$ActivityData = new SimpleXMLElement($xml);
$basePath = $ActivityData->children('soap',true)->Body->GetUserActivityDataResponse->GetUserActivityDataResult->ActArray->ACT;
foreach ($basePath as $userActivity)
{
$this->uGUID = $userActivity->UserGUID;
echo $this->uGUID."<br />";
}
}
The XML 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>
<GetUserActivityDataResponse xmlns="http://webservices.website.net/">
<GetUserActivityDataResult>
<ResponseCode>SUCCESS</ResponseCode>
<FailedUserCount>0</FailedUserCount>
<ActCount>1</ActCount>
<ActArray>
<ACT>
<UserGUID>0dc299ba-XXXX-XXXX-XXXX-7ca097d51eb6</UserGUID>
<ActDataCount>15</ActDataCount>
<ActData>
<ACT_DATA>
<Start>2012-03-05T08:40:00</Start>
<End>2012-03-05T09:00:00</End>
<SourceCount>1</SourceCount>
<SourceData>
<ACT_SRC_DATA>
<Source>ACTIPED</Source>
<TypeCount>3</TypeCount>
<TypeData>
<ACT_TYPE_DATA>
<Type>WALK</Type>
<S>40</S>
<C>2</C>
<D>20</D>
<T>16</T>
</ACT_TYPE_DATA>
<ACT_TYPE_DATA>
<Type>RUN</Type>
<S>20</S>
<C>2</C>
<D>20</D>
<T>10</T>
</ACT_TYPE_DATA>
<ACT_TYPE_DATA>
<Type>OTHER</Type>
<S>0</S>
<C>0</C>
<D>0</D>
<T>28</T>
</ACT_TYPE_DATA>
</TypeData>
<MetricCount>0</MetricCount>
</ACT_SRC_DATA>
</SourceData>
</ACT_DATA>
</ActData>
</ACT>
</ActArray>
<AsOfServerTimeGMT>2012-03-06T16:41:41.513</AsOfServerTimeGMT>
</GetUserActivityDataResult>
</GetUserActivityDataResponse>
</soap:Body>
</soap:Envelope>
Neither method works and both leave me with the same error:
Warning: Invalid argument supplied for foreach() in /c08/domains/dev.mysite.com/html/class/XMLParse.class.php on line 29
It says:
<GetUserActivityDataResponse xmlns="http://webservices.website.net/">
and you are trying to do
$basePath = $soapEnvelope
->children('soap', true)
->Body
->GetUserActivityDataResponse
…
which means you try to get <soap:GetUserActivityDataResponse> which obviously doesnt exist. You have to do (demo)
$basePath = $soapEnvelope
->children('soap', true)
->Body
->children('http://webservices.website.net/')
->GetUserActivityDataResponse
->GetUserActivityDataResult
->ActArray
->ACT;
Actually, you could just do ->children() to jump back to the default namespace, but I find providing the namespace explicitly somewhat clearer. Your choice.
Your XPath fails because you didn't specify the namespace for ActArray. Also, when xpath() is successful, it returns an array of SimpleXmlElements. You tried array->ACT, which doesn't work because an array is not an object. The first ActArray is in $basePath[0]. So you have to adjust the code to
$basePath = $soapEnvelope->xpath('//ns:GetUserActivityDataResult/ns:ActArray');
foreach ($basePath[0]->ACT as $userActivity) {
…
To get the ACT elements directly, change the XPath to
//ns:GetUserActivityDataResult/ns:ActArray/ns:ACT
Related
I'm creating SOAP web service using PHP.
Here is my code..
SoapServer.php
class server{
public function RegisterComplaint($strInputXml){
$str = "<RESULT><complaintNo>09865678</complaintNo></RESULT>";
$arr['RegisterComplaintResult'] = trim($str);
return $arr;
}
}
$custom_wsdl = 'custom.wsdl';
$server = new SoapServer($custom_wsdl);
$server->setClass('server');
$server->handle();
When I call RegisterComplaint using Wizdler(chrome extension) I get below result:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.Insurer.com/webservices/">
<SOAP-ENV:Body>
<ns1:RegisterComplaintResponse>
<ns1:RegisterComplaintResult><RESULT><complaintNo>09865678</complaintNo></RESULT></ns1:RegisterComplaintResult>
</ns1:RegisterComplaintResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Here I want result in below format(special characters to HTML entities):
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://www.Insurer.com/webservices/">
<SOAP-ENV:Body>
<ns1:RegisterComplaintResponse>
<ns1:RegisterComplaintResult><RESULT><complaintNo>09865678</complaintNo></RESULT></ns1:RegisterComplaintResult>
</ns1:RegisterComplaintResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Does any one know what I have to change for required output?
I tried html_entity_decode() & htmlspecialchars() on $str variable, but it's not working.
The solution as response. (Already quoted out in the comments)
The SoapServer class awaits an object as return value. This object will be automatically encoded by the server using the definitions from the used wsdl file. If a string is returned, its entities will always be encoded.
class Server
{
public function registerComplaint()
{
$registerComplaintResponse = new stdClass();
$registerComplaintResult = new stdClass();
$result = new \stdClass();
$result->complaintNo = '09865678';
$registerComplaintResult->RESULT = $result;
$registerComplaintResponse->RegisterComplaintResult = $registerComplaintResult;
return $registerComplaintResponse;
}
}
All definitions of return types (complex types) are defined in the wsdl file.
The issue: I am sending SOAP request to 3rd-party server and inside one of my tags I have all "<" ">" replaced with html-entities < >
The info:
Lets say I have this class(simplified and pseudocoded for clarity):
Class SoapSender {
private $session = 'sessionHash';
private $soap = new SoapClient(/* settings */);
public function create() {
try {
$agr = [];
$agr['SessionToken'] = $this->session;
$agr['Document'] = $this->prepareDocument();
$request = $this->soap->createRequest($agr); // 3rd-party call
} catch (SoapFault $f) {
/* handle exception */
}
}
The documentation of 3rd-party says that <Document> should be XML string so I do this:
private function prepareDocument() {
$arr = [
/* Create all sub-tags of <Document> */
];
$xml = Formatter::make($arr, 'array')->toXml();
// this operations required for valid structure
$xml = str_replace(array('<?xml version="1.0" encoding="utf-8"?>','<xml>','</xml>'), '', $xml);
$xml = str_replace(['Subject_1', 'Subject_2'], 'Subject', $xml);
$xml = str_replace(['Period_1', 'Period_2'], 'Period', $xml);
$xml = preg_replace('/Store_[1-9]/', 'Store', $xml);
return $xml;
Formatter is SoapBox/laravel-formatter.
Soo, when I send request and recieve response with errors I dump $this->soap->__getLastRequest() and see that:
<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://someurl.com">
<SOAP-ENV:Body><ns1:CreateRequest>
<Document>
<General><Product>Bread</Product><DateBeg>2016-04-04T00:00:00</DateBeg><DateEnd>2017-04-03</DateEnd><.....
...........blah-blah....
</Document>
<SessionToken>SessionTokeon</SessionToken></ns1:CreateRequest></SOAP-ENV:Body></SOAP-ENV:Envelope>
What I have so far: debuging prepareDocument says that I have valid xml string in utf-8 with all tags intact, so encoding them to html-entities happens on SOAP request. Only the Document tag gets encoded, others are ok.
All my other services that use same aproach but different 3rd-party works perfect. Sending this request (but decoded back to normal) by SOAP UI works as it should. All happens inside laravel project.
The issue again: I am sending request to 3rd-party server and inside one of my tags I have all "<" ">" replaced with html-entities < >
The question: What should I do to fix this issue?
I am trying to establish a communication with two zf2 application via curl.The required response is in xml. So far I could establish the connection and xml is returned as response.
The problem
The problem is that,I can't iterate on my xml response.Whenever I var_dump and view source code of my $response->getContent,I get as
string(142) "<?xml version="1.0" encoding="UTF-8"?>
<myxml>
<login>
<status>success</status>
<Err>None</Err>
</login>
</myxml>
"
and when I simply var_dump my $response,I get an object(Zend\Http\Response)#440.
simplexml_load_string($response->getContent()) gives me a blank page.
Also print $data->asXML() gives me Call to a member function asXML() on a non-object error.What am I doing wrong here?
Curl request action
$request = new \Zend\Http\Request();
$request->getHeaders()->addHeaders([
'Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8'
]);
$request->setUri('http://localhost/app1/myaction');
$request->setMethod('POST'); //uncomment this if the POST is used
$request->getPost()->set('curl', 'true');
$request->getPost()->set('email', 'me#gmail.com');
$request->getPost()->set('password', '2014');
$client = new Client;
$client->setAdapter("Zend\Http\Client\Adapter\Curl");
$response = $client->dispatch($request);
var_dump($response);//exit;
//$response = simplexml_load_string($response->getContent());
//echo $response;exit;
return $response;
Curl response action
$php_array=array(
'login'=>array(
'status'=>'failed','Err'=>'Unauthorised Access'
)
);
$Array2XML=new \xmlconverter\Arraytoxml;
$xml = $Array2XML->createXML('myxml', $php_array);
$xml = $xml->saveXML();
//echo $xml;exit;
$response = new \Zend\Http\Response();
$response->getHeaders()->addHeaderLine('Content-Type', 'text/xml; charset=utf-8');
$response->setContent($xml);
return $response;
The Array2XML can be found here
Any ideas?
when I simply var_dump my $response,I get an object(Zend\Http\Response)#440
This is correct and it tells you the type of $response.
simplexml_load_string($response->getContent()) gives me a blank page.
This is correct because despite this function can return a value expressible to an empty string, it does not create any output on it's own and therefore the blank page is to be expected.
Any ideas?
First of all you should formulate a proper problem statement with your question. All you say so far therein is to be expected, so your question is not clear at best.
Second you need to do proper error handling and do some safe programming:
$buffer = $response->getContent();
if (!is_string($buffer) || !strlen($buffer) || $buffer[0] !== '<') {
throw new RuntimeException('Need XML string, got %s', var_export($buffer, 1));
}
$xml = simplexml_load_string($buffer);
if (false === $xml) {
throw new RuntimeException('Unable to parse response string as XML');
}
Which is: For every parameter you get, validate it. For every function or method result you receive check the post-conditions. Before you call a function or method, check the pre-conditions for each parameter.
Log errors to file and handle uncaught exceptions.
As an additional idea: Drop the use of the array to XML function and replace it with a library that is maintained. In your case it's perhaps easier to just use SimpleXML your own to create the XML.
I use the following function to validate XML coming from a Web API before trying to parse it:
function isValidXML($xml) {
$doc = #simplexml_load_string($xml);
if ($doc) {
return true;
} else {
return false;
}
}
For some reason, it fails on the following XML. While it's a bit light in content, it looks valid to me.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><connection-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" />
Why would this fail? I tried another method of validate the XML that used DOMDocument and libxml_get_errors(), but it was actually more fickle.
EDIT: I should mention that I'm using PHP 5.3.8.
I think your interpretation is just wrong here – var_dump($doc) should give you
object(SimpleXMLElement)#1 (0) {
}
– but since it is an “empty” SimpleXMLElement, if($doc) considers it to be false-y due to PHP’s loose type comparison rules.
You should be using
if ($doc !== false)
here – a type-safe comparison.
(Had simplexml_load_string actually failed, it would have returned false – but it didn’t, see var_dump output I have shown above, that was tested with exactly the XML string you’ve given.)
SimpleXML wants some kind of "root" element. A self-closing tag at the root won't cut it.
See the following code when a root element is added:
<?php
function isValidXML($xml)
{
$doc = #simplexml_load_string($xml);
if ($doc) {
return true;
} else {
return false;
}
}
var_dump(isValidXML('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root><connection-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" /></root>'));
// returns true
print_r(isValidXML('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><root><connection-response-list xmlns="http://www.ca.com/spectrum/restful/schema/response" /></root>'));
// returns 1
?>
Hope that helps.
An API client I have developed works with XML messages and the messages are signed according to the XML Signature Syntax and Processing specification. After a long struggle, I finally got the signatures working.
At this moment I am building the XML with HEREDOC (simply php strings) and with a cleanup, I'd like to create the XML with DOMDocument directly. However, this causes the message to be invalidated by the server.
This is the current setup (server accepts this message when signed):
$xml = <<<EOT
<?xml version="1.0" encoding="UTF-8"?>
<DirectoryReq xmlns="http://www.idealdesk.com/ideal/messages/mer-acq/3.3.1" version="3.3.1">
<createDateTimestamp>$timestamp</createDateTimestamp>
<Merchant>
<merchantID>$merchantId</merchantID>
<subID>$subId</subID>
</Merchant>
</DirectoryReq>
EOT;
$document = new DOMDocument();
$document->loadXML($xml);
This is the OO approach (server rejects this message when signed):
$document = new DOMDocument('1.0', 'UTF-8');
$request = $document->createElement('DirectoryReq');
$xmlns = $document->createAttribute('xmlns');
$xmlns->value = 'http://www.idealdesk.com/ideal/messages/mer-acq/3.3.1';
$version = $document->createAttribute('version');
$version->value = '3.3.1';
$request->appendChild($xmlns);
$request->appendChild($version);
$merchant = $document->createElement('Merchant');
$merchant->appendChild($document->createElement('merchantID', $merchantId));
$merchant->appendChild($document->createElement('subID', $subId));
$request->appendChild($document->createElement('createDateTimestamp', $timestamp));
$request->appendChild($merchant);
$document->appendChild($request);
What can cause the difference as such the XML signature is invalidated by the server? The code to sign the message is exactly the same. The server is simply reporting "Invalid electronic signature".
If required I can show more code.
EDIT, more output and comparison of XML generated
To give some more information, this is the output of the first (HEREDOC) xml, generated via $document->saveXml():
<?xml version="1.0" encoding="UTF-8"?>
<DirectoryReq xmlns="http://www.idealdesk.com/ideal/messages/mer-acq/3.3.1" version="3.3.1">
<createDateTimestamp>2013-08-10T19:41:20.000Z</createDateTimestamp>
<Merchant>
<merchantID>0020XXXXXX</merchantID>
<subID>0</subID>
</Merchant>
</DirectoryReq>
This is the output ($document->saveXML()) for the second (direct DOMDocument generation) method:
<?xml version="1.0" encoding="UTF-8"?>
<DirectoryReq xmlns="http://www.idealdesk.com/ideal/messages/mer-acq/3.3.1" version="3.3.1">
<createDateTimestamp>2013-08-10T19:41:20.000Z</createDateTimestamp>
<Merchant>
<merchantID>0020XXXXXX</merchantID>
<subID>0</subID>
</Merchant>
</DirectoryReq>
In php, var_dump() gives the exact same string length. If I compare both strings (=== obviously) they are the same. Comparing both objects, then they are not the same.
Signing example
Signing occurs with the library xmlseclibs with this code (NB. both types are signed the same way!):
public function sign(DOMDocument $document, $fingerprint, $keyfile, $passphrase = null)
{
$dsig = new XMLSecurityDSig();
$dsig->setCanonicalMethod(XMLSecurityDSig::EXC_C14N);
$dsig->addReference($document, XMLSecurityDSig::SHA256,
array('http://www.w3.org/2000/09/xmldsig#enveloped-signature'),
array('force_uri' => true)
);
$key = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type' => 'private'));
if ($passphrase !== null) {
$key->passphrase = $passphrase;
}
$key->loadKey($keyfile, true);
$dsig->sign($key);
$dsig->addKeyInfoAndName($fingerprint);
$dsig->appendSignature($document->documentElement);
}
If I dump the XML after it's signed, the <DigestValue> and <SignatureValue> values are different. So the server is correct the signature is invalid, but I cannot come up with a clue why method A works and B not.
You are overwriting $merchant when you create the Merchant element, so just rename the variable
$merchantElement = $document->createElement('Merchant');
I have now solved it by exporting and importing the XML again. It's quite ugly, but allows me to flexibly handle the DOMNodes.
protected function repairDOMDocument(DOMDocument $document)
{
$xml = $document->saveXML();
$document = new DOMDocument;
$document->loadXML($xml);
return $document;
}
If there is a suggestion how to stop doing this, I am pleased to hear so.