Parsing XML in PHP with SimpleXML - php

I am trying to parse the below XML , i have tryed loads of different solutions, i have provided an example of what i have tryed. I have read the SimpleXML documents and i still cant get this right. In the Example below all im trying to do is Echo out a line in the XML.
<?php
$xmlstr = '
<?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>
<SubmitLeadResponse xmlns="https://test.com/">
<SubmitLeadResult>
<Result>C</Result>
<RedirectURL>https://testred.com</RedirectURL>
<ApplicantID>123</ApplicantID>
<ConfirmedPrice>0</ConfirmedPrice>
<PotentialPrice>0</PotentialPrice>
</SubmitLeadResult>
</SubmitLeadResponse>
</soap:Body>
</soap:Envelope>'
;
?>
<?php
$SubmitLeadResponse = new SimpleXMLElement($xmlstr);
echo $SubmitLeadResponse->SubmitLeadResult[0]->RedirectURL;
?>

You can try below code for SimpleXML
<?php
$xml ='<?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>
<SubmitLeadResponse xmlns="https://test.com/">
<SubmitLeadResult>
<Result>C</Result>
<RedirectURL>https://testred.com</RedirectURL>
<ApplicantID>123</ApplicantID>
<ConfirmedPrice>0</ConfirmedPrice>
<PotentialPrice>0</PotentialPrice>
</SubmitLeadResult>
</SubmitLeadResponse>
</soap:Body>
</soap:Envelope>';
$get_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $xml);
$xml = simplexml_load_string($get_xml);
print"<pre>";
print_r((string)$xml->Body->SubmitLeadResponse->SubmitLeadResult->RedirectURL);
echo "<br /><br /><br />";
print_r($xml);
?>

I've changed your code a bit. Here's a working sample to get the RedirectURL:
<?php
$xmlstr = '<?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>
<SubmitLeadResponse xmlns="https://test.com/">
<SubmitLeadResult>
<Result>C</Result>
<RedirectURL>https://testred.com</RedirectURL>
<ApplicantID>123</ApplicantID>
<ConfirmedPrice>0</ConfirmedPrice>
<PotentialPrice>0</PotentialPrice>
</SubmitLeadResult>
</SubmitLeadResponse>
</soap:Body>
</soap:Envelope>';
$doc = new DOMDocument();
$doc->loadXML( $xmlstr );
$RedirectURL = $doc->getElementsByTagName( "RedirectURL" );
$RedirectURL = $LoginResults->item(0)->nodeValue;
var_dump( $RedirectURL );
Sample provided from this source: There are also more informations to reading SOAP-envelopes without a soapclient
Please note that it's good practice to omit the php closing tag and stay in the php-context as long as possible to avoid unexpected outputs (linebreaks).

Your XML contains namespaced elements, so it's a little more complicated to parse. It can be done by passing the namespace values to children() like so:
Codepad demo
$SubmitLeadResponse = new SimpleXMLElement($xmlstr);
echo (string)$SubmitLeadResponse
->children('http://schemas.xmlsoap.org/soap/envelope/')
->Body
->children('https://test.com/')
->SubmitLeadResponse
->SubmitLeadResult
->RedirectURL;
Outputs
https://testred.com
Note: SimpleXML doesn't like new lines before the XML string, so remove the new line, making it:
$xmlstr = '<?xml version="1.0" encoding="utf-8"?>

Related

soap xml response - how to get that stubborn data out [duplicate]

This question already has answers here:
Reference - How do I handle Namespaces (Tags and Attributes with a Colon in their Name) in SimpleXML?
(2 answers)
Closed 3 years ago.
I'm trying to get the contents of the faultstring element and I'm more comfortable with SimpleXML's object syntax ($xml->...->faultstring.) The DomDocument method below works, but I'd prefer to stick with SimpleXML.
PHP version 5.6.40, Libxml 2.9.1.
$xmlResponse = '<?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>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Server did not recognize the value of HTTP Header SOAPAction: https://gw1.domain.com:4430/.</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>';
// DOES NOT WORK
$xml = simplexml_load_string($xmlResponse,NULL,NULL,"http://schemas.xmlsoap.org/soap/envelope/");
$faultstring = (string) ($xml->Body->Fault->faultstring);
var_dump($faultstring);
// WORKS
$_DomObject = new DOMDocument;
$_DomObject->loadXML($xmlResponse);
if (!$_DomObject) die("Error while parsing the document");
$s = simplexml_import_dom($_DomObject);
foreach(['faultcode','faultstring','detail'] as $tag) {
echo $tag.' => '.$_DomObject->getElementsByTagName($tag)[0]->textContent.'<br/>';
}
<?php
$xmlResponse = <<<XML
<?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>
<soap:Fault>
<faultcode>soap:Client</faultcode>
<faultstring>Server did not recognize the value of HTTP Header SOAPAction: https://gw1.domain.com:4430/.</faultstring>
<detail />
</soap:Fault>
</soap:Body>
</soap:Envelope>
XML;
XML namespaces are getting in the way; they're the soap: prefix on the element names. It's possible to register all the namespaces and get it working that way, but just using XPath is easier:
$xml = new SimpleXMLElement($xmlResponse);
$fault = $xml->xpath("//faultstring");
echo (string)$fault[0] . "\n";
And here's how it looks using namespaces. You still get the object syntax, but it becomes a lot more complicated.
$xml = new SimpleXMLElement($xmlResponse);
$fault = $xml->children("soap", true)->Body->children("soap", true)->Fault->children()->faultstring;
echo (string)$fault . "\n";
Output for both:
Server did not recognize the value of HTTP Header SOAPAction: https://gw1.domain.com:4430/.

parse the soap xml response to array

I had used curl to call the soap server and i got the response like this:
<?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:Body>
<GenerateAuthPasswordResponse xmlns="NepalTelecom.AuthGateway">
<GenerateAuthPasswordResult>abcd-efgh</GenerateAuthPasswordResult>
<ResultCode>1</ResultCode>
</GenerateAuthPasswordResponse>
</soap:Body>
</soap:Envelope>
and when i tried to parse the soap xml as:
$response = $this->SoapModel->soapCall($xml , $this->vas_wsdl_url);
$obj = simplexml_load_string($response);
echo $obj;die();
[Note: where $response is the above soap response provided in soap xml]
and i get the $obj as some error like this:
Severity: Warning
Message: simplexml_load_string(): namespace warning : xmlns: URI NepalTelecom.AuthGateway is not absolute
please any body could help so fix this issue.
Thank you in advance.
Try this.
<?php
$xml = '<?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:Body>
<GenerateAuthPasswordResponse >
<GenerateAuthPasswordResult>abcd-efgh</GenerateAuthPasswordResult>
<ResultCode>1</ResultCode>
</GenerateAuthPasswordResponse>
<GenerateAuthPasswordResponse >
<GenerateAuthPasswordResult>abcd-efgh</GenerateAuthPasswordResult>
<ResultCode>1</ResultCode>
</GenerateAuthPasswordResponse>
</soap:Body>
</soap:Envelope>';
$xml = simplexml_load_string($xml, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$ns = $xml->getNamespaces(true);
$soap = $xml->children($ns['soap']);
$res = $soap->Body->children();
print_r($res);

XML interpretation issue

I am working using soap, when the soap response is sent back all the < and > are represented using special characters.
<?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">
<UploadFileNew_XMLResponse xmlns="http://tempuri.org/GAPS_Uploader/FileUploader">
<UploadFileNew_XMLResult>
<?xml version="1.0" encoding="utf-8"?><Response><ResCode>1009</ResCode><Message>3 transaction(s) failed</Message><Errors><Error><Rownum>1</Rownum><Description>: Reference already exist </Description><Res_Code>59b1ebbc1c012 </Res_Code></Error><Error><Rownum>2</Rownum><Description>: Reference already exist </Description><Res_Code>59cb93d6c1d30 </Res_Code></Error><Error><Rownum>3</Rownum><Description>: Reference already exist </Description><Res_Code>59cbaca456589 </Res_Code></Error></Errors></Response>
</UploadFileNew_XMLResult>
</UploadFileNew_XMLResponse>
</soap:Envelope>
please how can i simplexml_load_string to process this result.
$response = htmlspecialchars_decode($response);
$parser = simplexml_load_string($response);
print_r($parser);
Change the order:
$parser = simplexml_load_string($response);
$response = htmlspecialchars_decode($parser->UploadFileNew_XMLResponse->UploadFileNew_XMLResult);
print_r($response);

Print specific element consuming SOAP with XML

I'm using the integrated SOAP client in PHP 5.3 and I've tested with this web service: http://www.webservicex.net/globalweather.asmx
I'm calling this method 'GetWeather' and the XML request looks like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetWeather xmlns="http://www.webserviceX.NET">
<CityName>string</CityName>
<CountryName>string</CountryName>
</GetWeather>
</soap:Body>
</soap:Envelope>
and response XML is like this:
<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetWeatherResponse xmlns="http://www.webserviceX.NET">
<GetWeatherResult>string</GetWeatherResult>
</GetWeatherResponse>
</soap:Body>
</soap:Envelope>
So far I'm getting successfully the array with this code:
<?php
$client = new SoapClient('http://www.webservicex.net/globalweather.asmx?WSDL');
$result = $client->GetWeather(array('CityName' => 'Barcelona', 'CountryName' => 'Spain'));
print_r ($result);
How can I print specific element, let's say the value of the CityName?
So when I want to print the city like this:
echo '<div> ' . $city . '</div>';
How do I get the value of the CityName?

Struggling to read a node with SimpleXML

Here is my XML response from an API:
<?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>
<GetCertificateResponse xmlns="http://url.com">
<GetCertificateResult>
<ReturnValue xmlns="">
<Status>Success</Status>
<Message/>
<CertificateNumber/>
<URL/>
</ReturnValue>
</GetCertificateResult>
</GetCertificateResponse>
</soap:Body>
</soap:Envelope>
How can I reaq the status node? I've tried so many combos:
$getCertificateXMLResponse = simplexml_load_string($getCertificateXMLResponse);
echo $getCertificateXMLResponse->GetCertificateResponse->GetCertificateResult->ReturnValue->Status;
You can also do it with Xpath
$xml = simplexml_load_string($soap, NULL, NULL, "http://schemas.xmlsoap.org/soap/envelope/");
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$result = $xml->xpath('//Status');
echo $result[0];
it's... ugly.. but works
$xml = new SimpleXMLElement(file_get_contents('a.xml'),0,false,'');
$namespaces = $xml->getDocNamespaces(true);
$xml->registerXPathNamespace('empty', $namespaces['']);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$status = array_shift($xml->xpath("soap:Body/empty:GetCertificateResponse/empty:GetCertificateResult/ReturnValue/Status"));
echo $status->asXML();
i'm curious to see more elegant solution.
and indeed take a look at things like nusoap.

Categories