Get xml response 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:

Читайте также:  Discord api java gradle

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; 

Источник

Parse An XML Response With PHP

If you’re like me, you find XML a real pain to deal with, but yet it still seems to exist with various web services. If you’re using Android or AngularJS, these frameworks can’t process XML out of the box, but they can JSON.

With the assistance of a PHP powered web server, you can easily transform the nasty XML responses you get into something more usable like JSON.

PHP has a nifty method called simplexml_load_string and what it does is it loads an XML structured string into an easy to use object. Let’s say you have a string variable called $xmlResponse that has the following properly formatted XML in it:

   Code Blog  Nic Raboy    Nic  Raboy    Maria  Campos    

Doing the following in PHP will give us a very nice object to work with:

$xml = simplexml_load_string($xmlResponse); 

Now to do the full conversion from object to JSON, I will be using ZendFramework 2. However, manipulations of the XML object can be done without a special framework or tool.

Let’s start by creating an array of our employees:

$employees = array(); foreach($xml->employees as $employee)   $employeeObject = array(  "firstname" => $employee->firstname,  "lastname" => $employee->lastname  );  array_push($employees, $employeeObject); > 

The above code will create a custom object for each employee in the XML and append them to an array. This will leave us with an array of employee objects customized to our liking.

The next thing we want to do is add the employees array to a custom object that has the rest of our business information in it:

$jsonObject = array(  "company" => $xml->company,  "owner" => $xml->owner,  "employees" => $employees ); 

Like I mentioned previously, I use ZendFramework 2 so I’ll be converting our custom object using the included Json methods. To convert to JSON, you would make a call like the following:

If everything went well, the JSON result of our XML response should look something like this:

  "company": "Code Blog",  "owner": "Nic Raboy",  "employees": [    "firstname": "Nic",  "lastname": "Raboy"  >,    "firstname": "Maria",  "lastname": "Campos"  >  ] > 

If you have your web server display the JSON response instead of the raw XML, your clients are going to have a much easier time absorbing it.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.

Источник

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