Soap response to array php

Parsing SOAP XML response with php

One of the simplest ways to handle namespace prefixes is simply to strip them from the XML response before passing it through to simplexml such as below:,PHP version > 5.0 has a nice SoapClient integrated. Which doesn’t require to parse response xml. Here’s a quick example, This works but only with static xml passed to the «$xml» variable. Return empty result when passed SOAP Response to it. – Sonu Singh Jadoun Feb 12 ’20 at 13:16 ,In your code you are querying for the payment element in default namespace, but in the XML response it is declared as in http://apilistener.envoyservices.com namespace.

One of the simplest ways to handle namespace prefixes is simply to strip them from the XML response before passing it through to simplexml such as below:

$your_xml_response = ''; $clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $your_xml_response); $xml = simplexml_load_string($clean_xml); 

This would return the following:

SimpleXMLElement Object ( [Body] => SimpleXMLElement Object ( [PaymentNotification] => SimpleXMLElement Object ( [payment] => SimpleXMLElement Object ( [uniqueReference] => ESDEUR11039872 [epacsReference] => 74348dc0-cbf0-df11-b725-001ec9e61285 [postingDate] => 2010-11-15T15:19:45 [bankCurrency] => EUR [bankAmount] => 1.00 [appliedCurrency] => EUR [appliedAmount] => 1.00 [countryCode] => ES [bankInformation] => Sean Wood [merchantReference] => ESDEUR11039872 ) ) ) ) 

Answer by Aubrie Hopkins

Simply calling $xml->SOAP-ENV:Envelope will result in an error due to the fact that hyphens and colons are not valid characters for object variables or methods. Whenever you are entering a new namespace, you can use SimpleXMLElement::children() to define the name space. The second argument tells the method that you are defining a prefix and not a namespace URL.,Please note that the SimpleXMLElement::children() method will always return a SimpleXMLElement whether the node has any children or not.,Setting an authorization header when using file_get_contents with PHP, Extreme Teams: Why Pixar, Netflix, AirBnB, and Other Cutting-Edge Companies Succeed Where Most Fail

// Mocks our SOAP response $soap_response =     Parsing SOAP responses with SimpleXML Awesome post about parsing SOAP responses. 2014-07-13 Josh Sherman @joshtronic  http://phpave.com/parsing-soap-responses-with-simplexml/  How to parse XML with SimpleXML Awesome post about parsing XML. 2014-07-29 Josh Sherman @joshtronic  http://phpave.com/how-to-parse-xml-with-simplexml/     XML; // Loads the XML $xml = simplexml_load_string($soap_response); // Grabs the posts $posts = $xml->children('SOAP-ENV', true)->Body->children('ns1', true)->Posts->Post; // Take the posts and generate some markup foreach ($posts as $post) < $twitter_url = 'https://twitter.com/' . $post->Author->Twitter; echo ' 

' . $post->Title . '

' . $post->Author->Name . '

' . $post->Description . '

Link . '">Read Article
'; >

Answer by Ramon Berg

I’m afraid I’m at a loss on how to parse this XML with namespaces and prefixes. Here’s the SOAP reply I get from a Curl request:,XML namespaces are used for providing uniquely named elements and attributes in an XML document:,First I use curl to login and send the SOAP request as outlined in this answer: https://stackoverflow.com/a/7157785/1121877,The rate data can be accessed like this:

Читайте также:  Php вставить в массив другой массив

I’m afraid I’m at a loss on how to parse this XML with namespaces and prefixes. Here’s the SOAP reply I get from a Curl request:

Edit: here’s some things I’ve tried (amongst others):

$xml = simplexml_load_string($soap); $result = $xml->children('http://schemas.xmlsoap.org/soap/envelope/') ->children('https://service.printapi.de/interface/') ->getproductpricekonfigurationresult ->objektpreisnetto; echo $result->objektpreisnetto; 

Here’s an even more basic example I tried, which also returns nothing:

$xml = simplexml_load_string($soap); foreach ($xml->children('http://schemas.xmlsoap.org/soap/envelope/') as $child) < echo "Child node: " . $child . "
"; >

Answer by Tyson Sosa

If you can’t use SoapClient to retrieve the SOAP response in a PHP object, then use SimpleXML to parse the soap response.,For example (where $xmlstr contains the SOAP response):,The best solution would be to use PHP’s SoapClient class to do the call which will return you an object and then converting this object to an array, like so:,I want to convert a soap xml response and store it in a database. Here is the XML that I have.

I want to convert a soap xml response and store it in a database. Here is the XML that I have.

     200 example2 ex2 [email protected]e2.com example2, example2 example2, example2 example2 111111 1111111111 11.11,-11.11 /example2/exam2/ex2      

Answer by Zavier Johnston

   VENDORKEYAUTHORIZED8e072cc1a 
 true)); $params->vendorKey = 'blahblah'; $params->dealerId = 'fakename'; $submit = $client->GetAuthToken($params); $response = $client->__getLastResponse(); $xmlString = preg_replace("/(]*>)/", "$1$2$3", $response); $xml = SimpleXML_Load_String($xmlString); $xml = new SimpleXMLElement($xml->asXML()); $parse = $xml->soapBody->GetAuthTokenResponse->GetAuthTokenResult; $token_xml = new SimpleXMLElement($parse->asXML()); $token = simplexml_load_string($token_xml); $AuthToken = $token->Status->Message; echo $AuthToken; ?> 

Answer by Presley Portillo

I found a perfect solution to parse SOAP response to an Array:,we can get body of the response from SOAP the following ways,The following SOAP response structure can be easily converted in an array using a combination of the previous methods. Using only the the function «simplexml_load_string» removing the colon «:» it returned null in some cases.

SOAP Response

    94567 3958 3 Declinada 202 93815.0 86815.0 0.0 COP 24-07-2015 12:18:40 PM REJECT 1 VISA 411111 1111  3      

PHP conversion:

$response = preg_replace("/(]*>)/", "$1$2$3", $response); $xml = new SimpleXMLElement($response); $body = $xml->xpath('//SBody')[0]; $array = json_decode(json_encode((array)$body), TRUE); print_r($array); 
Array ( [ns2transaccionResponse] => Array ( [respuestaTransaccion] => Array ( [idTransaccion] => 94567 [referencia] => 3958 [idEstado] => 3 [nombreEstado] => Declinada [codigoRespuesta] => 202 [valor] => 93815.0 [iva] => 86815.0 [baseDevolucion] => 0.0 [isoMoneda] => COP [fechaProcesamiento] => 24-07-2015 12:18:40 PM [mensaje] => REJECT [tarjetaRespuesta] => Array ( [idFranquicia] => 1 [nombreFranquicia] => VISA [numeroBin] => 411111 [numeroProducto] => 1111 ) [procesadorRespuesta] => Array ( [idProcesador] => 3 ) ) ) ) 

I found a perfect solution to parse SOAP response to an Array:

$plainXML = mungXML( trim($soapXML) ); $arrayResult = json_decode(json_encode(SimpleXML_Load_String($plainXML, 'SimpleXMLElement', LIBXML_NOCDATA)), true); print_r($arrayResult); // FUNCTION TO MUNG THE XML SO WE DO NOT HAVE TO DEAL WITH NAMESPACE function mungXML($xml) < $obj = SimpleXML_Load_String($xml); if ($obj === FALSE) return $xml; // GET NAMESPACES, IF ANY $nss = $obj->getNamespaces(TRUE); if (empty($nss)) return $xml; // CHANGE ns: INTO ns_ $nsm = array_keys($nss); foreach ($nsm as $key) < // A REGULAR EXPRESSION TO MUNG THE XML $rgx = '#' // REGEX DELIMITER . '(' // GROUP PATTERN 1 . '\' // A COLON (EXACTLY ONE) . ')' // END GROUP PATTERN . '#' // REGEX DELIMITER ; // INSERT THE UNDERSCORE INTO THE TAG NAME $rep = '$1' // BACKREFERENCE TO GROUP 1 . '_' // LITERAL UNDERSCORE IN PLACE OF GROUP 2 ; // PERFORM THE REPLACEMENT $xml = preg_replace($rgx, $rep, $xml); > return $xml; > // End :: mungXML() 
$xml = new SimpleXMLElement($soapResponse); foreach($xml->xpath('//soap:body') as $header) < $output = $header->registerXPathNamespace('default', 'http://FpwebBox.Fareportal.com/Gateway.asmx'); > 
$doc = new DOMDocument('1.0', 'utf-8'); $doc->loadXML( $soapResponse ); $XMLresults = $doc->getElementsByTagName("SearchFlightAvailability33Response"); $output = $XMLresults->item(0)->nodeValue; 

Источник

Читайте также:  Java system configuration properties

How to convert SOAP response to PHP Array?

The following SOAP response structure can be easily converted in an array using a combination of the previous methods. Using only the the function «simplexml_load_string» removing the colon «:» it returned null in some cases.

SOAP Response

    94567 3958 3 Declinada 202 93815.0 86815.0 0.0 COP 24-07-2015 12:18:40 PM REJECT 1 VISA 411111 1111  3      

PHP conversion:

$response = preg_replace("/(]*>)/", "$1$2$3", $response); $xml = new SimpleXMLElement($response); $body = $xml->xpath('//SBody')[0]; $array = json_decode(json_encode((array)$body), TRUE); print_r($array); 
Array ( [ns2transaccionResponse] => Array ( [respuestaTransaccion] => Array ( [idTransaccion] => 94567 [referencia] => 3958 [idEstado] => 3 [nombreEstado] => Declinada [codigoRespuesta] => 202 [valor] => 93815.0 [iva] => 86815.0 [baseDevolucion] => 0.0 [isoMoneda] => COP [fechaProcesamiento] => 24-07-2015 12:18:40 PM [mensaje] => REJECT [tarjetaRespuesta] => Array ( [idFranquicia] => 1 [nombreFranquicia] => VISA [numeroBin] => 411111 [numeroProducto] => 1111 ) [procesadorRespuesta] => Array ( [idProcesador] => 3 ) ) ) ) 

Solution 3

I found a perfect solution to parse SOAP response to an Array:

$plainXML = mungXML( trim($soapXML) ); $arrayResult = json_decode(json_encode(SimpleXML_Load_String($plainXML, 'SimpleXMLElement', LIBXML_NOCDATA)), true); print_r($arrayResult); // FUNCTION TO MUNG THE XML SO WE DO NOT HAVE TO DEAL WITH NAMESPACE function mungXML($xml) < $obj = SimpleXML_Load_String($xml); if ($obj === FALSE) return $xml; // GET NAMESPACES, IF ANY $nss = $obj->getNamespaces(TRUE); if (empty($nss)) return $xml; // CHANGE ns: INTO ns_ $nsm = array_keys($nss); foreach ($nsm as $key) < // A REGULAR EXPRESSION TO MUNG THE XML $rgx = '#' // REGEX DELIMITER . '(' // GROUP PATTERN 1 . '\' // A COLON (EXACTLY ONE) . ')' // END GROUP PATTERN . '#' // REGEX DELIMITER ; // INSERT THE UNDERSCORE INTO THE TAG NAME $rep = '$1' // BACKREFERENCE TO GROUP 1 . '_' // LITERAL UNDERSCORE IN PLACE OF GROUP 2 ; // PERFORM THE REPLACEMENT $xml = preg_replace($rgx, $rep, $xml); > return $xml; > // End :: mungXML() 

It will give you a perfect array of SOAP XML Data.

Solution 4

Php parse SOAP response to an array

 $xml = file_get_contents($response); // SimpleXML seems to have problems with the colon ":" in the response tags, so take them out $xml = preg_replace(“/(]*>)/”, “$1$2$3″, $xml); $xml = simplexml_load_string($xml); $json = json_encode($xml); $responseArray = json_decode($json,true); 

Solution 5

I got a single value using DOMDocument.

 $soap_response = $client->__getLastResponse(); $dom_result = new DOMDocument; if (!$dom_result->loadXML($soap_response)) throw new Exception(_('Error parsing response'), 11); $my_val = $dom_result->getElementsByTagName('my_node')->item(0)->nodeValue; 

Источник

Читайте также:  Requires php extension mysql

Converting SOAP response into PHP array: A Guide

In addition, managing the response will be effortless since you will be familiar with the PHP objects created as PHP classes in the SDK. Regarding converting SOAP XML responses to PHP objects or arrays, I discovered a solution by following the method suggested by @lalithkumar. Nonetheless, I appreciate the assistance.

Converting SOAP XML response to a PHP object or array

The sole resolution that proved effective for me is.

$xml = $soap_xml_result; $xml = preg_replace("/(]*>)/", '$1$2$3', $xml); $xml = simplexml_load_string($xml); $json = json_encode($xml); $responseArray = json_decode($json, true); // true to have an array, false for an object print_r($responseArray); 

While the suggestion regarding bksi is not entirely incorrect, it is worth noting that, since we are dealing with XML, it is essential to access the namespaced elements correctly. This can be achieved more efficiently by registering the namespace-uri to your preferred prefix and using an XPath expression.

$soap = simplexml_load_string($soapXMLResult); $soap->registerXPathNamespace('ns1', 'http://ivectorbookingxml/'); $test = (string) $soap->xpath('//ns1:SearchResponse/ns1:SearchResult/ns1:SearchURL[1]')[0]; var_dump($test); 
string(100) "http://www.lowcostholidays.fr/dl.aspx?p=0,8,5,0&date=10/05/2013&duration=15&room1=2,1,0_5®ionid=9" 

To navigate without XPath, you must designate the namespace while traversing. Only the children within the namespace of the element itself are accessible directly if the element is unprefixed. Since the root element is prefixed, you must initially move up to the response.

$soap = simplexml_load_string($soapXMLResult); $response = $soap->children('http://schemas.xmlsoap.org/soap/envelope/') ->Body->children() ->SearchResponse ; 

Utilize the variable labeled as $response in the way you are familiar with.

$test = (string) $response->SearchResult->SearchURL; 

Since the returned result is more complex and all the response values can be conveniently accessed, it is likely the best option despite the lack of a prefix for that element.

Your question is similar to:

The descriptions and code available there may prove to be beneficial.

One way to handle the SOAP response is by converting it into a DOM Document first and then transforming it into a simplexml object.

loadHTML($soap_response); libxml_clear_errors(); $xml = $doc->saveXML($doc->documentElement); $xml = simplexml_load_string($xml); $response = $xml->body->envelope->body->searchresponse; //print_r($response); exit; echo $response->searchresult->returnstatus->success; echo '
'; echo $response->searchresult->searchurl; ?>

Although it is effective, there may be issues when dealing with certain characters in your reply, such as é and à.

Soap — Returning a PHP Array from a PHP SoapServer, This will convert your stdClass object into an array, there is no measurable overhead to this, and is O(1) in PHP. You may want to try changing the type from xsd:object to …

Manually convert XML SOAP response into PHP array

Источник

Оцените статью