Using XML Data as Array - php

I have a problem, I'm trying to get data from http://www.acquaintcrm.co.uk/propertyfunctions/propertysearch.asmx?op=GetDataV8
I have made the request and output the data to a file, properties.xml
The file gets filled with data, but I just dont know how to use that data, I would like to convert the xml data into an array, but I honestly don't know where to start.
My code
$xml_data = '<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>
<GetDataV8 xmlns="http://www.AcquaintCRM.co.uk/propertyfunctions/">
<strSitePrefix>STDZ</strSitePrefix>
<intSiteID>-1</intSiteID>
<intPropertyID>0</intPropertyID>
<intPropertyDevelopmentID>0</intPropertyDevelopmentID>
<bytBedrooms>0</bytBedrooms>
<decMinPrice>0</decMinPrice>
<decMaxPrice>0</decMaxPrice>
<bytTenure>1</bytTenure>
<intCommercial>-1</intCommercial>
<bytPropertyAge>0</bytPropertyAge>
<intRentalTerms>0</intRentalTerms>
<bytFeaturedCount>0</bytFeaturedCount>
<strAreas></strAreas>
<strTypes></strTypes>
<bytSortOrder>0</bytSortOrder>
<bytUseCDataTags>0</bytUseCDataTags>
</GetDataV8>
</soap:Body>
</soap:Envelope>
';
$url = "http://www.acquaintcrm.co.uk/propertyfunctions/propertysearch.asmx?op=GetDataV8";
$headers = array(
"POST * HTTP/1.1",
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Content-length: ".strlen($xml_data),
"SOAPAction: http://www.AcquaintCRM.co.uk/propertyfunctions/GetDataV8",
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
$response = curl_exec($ch);
if (curl_errno($ch))
{
echo 'Error: ';
echo curl_error($ch);
}
else
{
curl_close($ch);
$xml = file_put_contents('properties.xml', $response);
$xml = simplexml_load_file('properties.xml');
print_r($xml);
}
The XML file can be viewed here
http://manchester.studentdigz.com/properties.xml
Thank you all in advance, I appreciate all help!

You can use php simplexml (http://php.net/manual/en/book.simplexml.php) to load the string in an object.
Note that if you really want an array you could as well do :
$xml = simplexml_load_string($xmlstring)->children('http://schemas.xmlsoap.org/soap/envelope/')->children('Body');
$json = json_encode($xml);
$array = json_decode($json,TRUE);
echo "<pre>";
echo "xml object : <br/>";
var_dump($xml);
echo "<hr/>";
echo "json string : <br/>";
var_dump($json);
echo "<hr/>";
echo "array : <br/>";
var_dump($array);

Related

Cannot parse Curl Response from Soap Service (Post petition)

im trying to parse a curl response for this request:
$soapUrl = "https://soap_example_url.com/log_in";
// xml post structure
$xml_post_string = '
<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:debisys-soap-services">
<soapenv:Body>
<urn:Login soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<version xsi:type="xsd:string">'.$version.'</version>
<userName xsi:type="xsd:string">'.$userName.'</userName>
<password xsi:type="xsd:string">'.$password.'</password>
<languageOption xsi:type="xsd:string">'.$language.'</languageOption>
</urn:Login>
</soapenv:Body>
</soapenv:Envelope>
';
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
But when i try to parse "$response2" i get nothing:
$xml = simplexml_load_string($response2);
$json = json_decode(json_encode($xml));
echo json_encode($xml, JSON_PRETTY_PRINT);
Here's what i get:
SimpleXMLElement Object ( )
{}
print_r: stdClass Object ( )
When i use print_r ($response2); function i get this in my browser:
<Login2Response><Version>01</Version><SiteID>xxxx</SiteID><ClerkId>xxxxx</ClerkId><ResponseCode>00</ResponseCode><ResponseMessage>user logged in</ResponseMessage></Login2Response>
And when i use "json_encode" i get this:
"\n \n \n <LoginResponse><Version>01<\/Version><SiteID>xxxxx<\/SiteID><ClerkId>xxxxx<\/ClerkId><ResponseCode>00<\/ResponseCode><ResponseMessage>user logged in<\/ResponseMessage><\/LoginResponse><\/return>\n <\/ns1:Login2Response>\n <\/soapenv:Body>\n<\/soapenv:Envelope>\n"
So i tried copy/paste the xml from my browser to a variable like this:
$returned_xml = '<LoginResponse><Version>01</Version><SiteID>xxxxx</SiteID><ClerkId>xxxxx</ClerkId><ResponseCode>00</ResponseCode><ResponseMessage>user logged in</ResponseMessage></LoginResponse>';
And it works, but i need to use $response2 to make it dynamically, thanks in advance.
I'm closer i did this:
$response2 = preg_replace('/(<\/?)(\w+):([^>]*>)/', '$1$2$3', $response2);
$xml = simplexml_load_string($response2);
$xml = var_dump($xml);
echo '<br><br>';
print_r($xml);
And now i'm getting this response:
object(SimpleXMLElement)#1 (1) { ["soapenvBody"]=> object(SimpleXMLElement)#2 (1) { ["ns1Login2Response"]=> object(SimpleXMLElement)#3 (1) { ["return"]=> string(194) "018821909123400USER LOGGED IN SUCCESSFULLY" } } }
How can i access to only the ["return"] response to parse it as json object?

PHP cURL submit to WSDL SOAP environment

I've never had the opportunity to submit to a WSDL SOAP web service and am running into some issues. Im using PHP cURL to submit the form to a known back end fist, then secondly to the WSDL SOAP service. The first part is working fine, so I will skip over that. I have spent the better part of 3 days trying different solutions I've found on the web, and my own after reading SOAP documentation, with no luck.
Here is what I'm using to submit to the WSDL
<?php
//first cURL POST HERE - works fine
//second cURL POST BELOW
$FName = $_POST['FirstName'];
$Lname = $_POST['LastName'];
$Email = $_POST['Email'];
$Phone = $_POST['Phone1'];
$soapURL = "https://something.com/IBWeb/IBDemoManager/IBDemoManager.asmx?wsdl";
$soapUser = "USR";
$soapPassword = "PWD";
$hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']);
$xml_post_string = '<soapenv:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://webservices.htdocs.openecry">
<soapenv:Header/>
<soapenv:Body>
<web:demosetup soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<AccessCode xsi:type="xsd:string">G0!=#%fut40</AccessCode>
<NewUserCategoryName xsi:type="xsd:string">OFLDemo</NewUserCategoryName>
<TemplateUserName xsi:type="xsd:string">OFLUser</TemplateUserName>
<CusType xsi:type="xsd:string">Indirect</CusType>
<WLabelID xsi:type="xsd:string">276</WLabelID>
<SCodeID xsi:type="xsd:string"></SCodeID>
<SoftID xsi:type="xsd:string">1</SoftID>
<FName xsi:type="xsd:string">'.$FName.'</FName>
<LName xsi:type="xsd:string">'.$LName.'</LName>
<Email xsi:type="xsd:string">'.$Email.'</Email>
<Phone xsi:type="xsd:string">'.$Phone.'</Phone>
<Address xsi:type="xsd:string"></Address>
<City xsi:type="xsd:string"></City>
<Zip xsi:type="xsd:string"></Zip>
<State xsi:type="xsd:string"></State>
<Country xsi:type="xsd:string"></Country>
<CountryName xsi:type="xsd:string"></CountryName>
<AssetTypes xsi:type="xsd:string">Futures</AssetTypes>
<How xsi:type="xsd:string">OFL webservice</How>
<MoreEmail xsi:type="xsd:string"></MoreEmail>
<RemoteAddr xsi:type="xsd:string">'.$hostname.'</RemoteAddr>
<CampaignID xsi:type="xsd:string"></CampaignID>
</web:demosetup>
</soapenv:Body>
</soapenv:Envelope>';
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
//IS SOAPAction the same as the endpoint "$soapURL"?//
"SOAPAction: https://something.com/IBWeb/IBDemoManager/IBDemoManager.asmx?wsdl",
"Content-length: ".strlen($xml_post_string),
);
$url2 = $soapURL;
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, $url2 );
curl_setopt($soap_do, CURLOPT_HEADER, false);
curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 100);
curl_setopt($soap_do, CURLOPT_TIMEOUT, 100);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($soap_do, CURLOPT_POST, true );
curl_setopt($soap_do, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $headers);
if(curl_exec($soap_do) === false) {
$err = 'Curl error: ' . curl_error($soap_do);
curl_close($soap_do);
print $err;
} else {
$result = curl_exec($soap_do);
echo '<pre>';
print_r($result);
curl_close($soap_do);
//print 'Operation completed without any errors';
}
Here are just some comments:
Try to disable the SSL check (just for testing):
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, 0);
You should call curl_close($ch2); as last. Example:
$output2 = curl_exec($ch2);
if(curl_errno($ch2))
echo curl_error($ch2);
} else {
echo $output2;
}
curl_close($ch2); // <--- close here
You could also try the Zend SOAP library.
If you don't like CURL try Guzzle to make an HTTP request.

XML RESPONSE CONVERT INTO ARRAY

XML response want to convert into PHP array it works fine in $response but when I convert into an array it will become empty. How can I convert this XML into an array to display it on the web page? Any information that would point me in the correct direction would be great.
$soapUrl = "http://api.rlcarriers.com/1.0.2/RateQuoteService.asmx"; // asmx URL of WSDL
$xml_post_string = '<?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>
<GetRateQuote xmlns="http://www.rlcarriers.com/">
<APIKey>UtN0YWEGRhOjNiNmItODRkMS00NzgyLThiYzNTViEzNjODNmC</APIKey>
<request>
<QuoteType>Domestic</QuoteType>
<CODAmount>0</CODAmount>
<Origin>
<City>New York</City>
<StateOrProvince>NY</StateOrProvince>
<ZipOrPostalCode>10001</ZipOrPostalCode>
<CountryCode>USA</CountryCode>
</Origin>
<Destination>
<City>New York</City>
<StateOrProvince>NY</StateOrProvince>
<ZipOrPostalCode>10009</ZipOrPostalCode>
<CountryCode>USA</CountryCode>
</Destination>
<Items>
<Item>
<Class>150.0</Class>
<Weight>2.5</Weight>
<Width>2.5</Width>
<Height>2.5</Height>
<Length>2.1</Length>
</Item>
</Items>
<DeclaredValue>120</DeclaredValue>
<Accessorials>
<Accessorial>ResidentialPickup</Accessorial>
<Accessorial>ResidentialDelivery</Accessorial>
</Accessorials>
<OverDimensionPcs>0</OverDimensionPcs>
</request>
</GetRateQuote>
</soap:Body>
</soap:Envelope>';
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://www.rlcarriers.com/GetRateQuote",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);exit;
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);
Below is the response received from the above code.
string(4037) "trueNEW YORKNY10001USANEW YORKNY10009USALISLong Island,
NY113781-888-575-2632MASPETHNYLISLong Island,
NY113781-888-575-2632MASPETHNY$420.352$442.90$8.86MINIMUM$510.35DISCNTFloor$420.35DISCNF$90.00FUEL23.1%$20.79ARBMH$65.00RPUCWT$132.30RCCWT$132.30NET$440.39STD71825391$839.95$440.39GSDS297780121$38.90$479.29GSAM382622281$77.70$518.09"
Those are SOAP XML, change it's heading by
...
// converting
$response = curl_exec($ch);
curl_close($ch);
$clean_xml = str_ireplace(['SOAP-ENV:', 'SOAP:'], '', $response);
$xml = simplexml_load_string($clean_xml);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
print_r($array);
see: How to parse SOAP XML?

PHP SOAP request with post method

I have a code here and can get only current oil price but I need to get a result the same as the picture below. I have no idea to do this.
<?php
$soapUrl = "http://www.pttplc.com/webservice/pttinfo.asmx?op=CurrentOilPrice";
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<CurrentOilPrice xmlns="http://www.pttplc.com/ptt_webservice/">
<Language>string</Language>
</CurrentOilPrice>
</soap12:Body>
</soap12:Envelope>';
$headers = array(
"POST /webservice/pttinfo.asmx HTTP/1.1",
"Host: www.pttplc.com",
"Content-Type: application/soap+xml; charset=utf-8",
"Content-Length: " . strlen($xml_post_string)
);
$url = $soapUrl;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
$response1 = str_replace("<soap:Body>", "", $response);
$response2 = str_replace("</soap:Body>", "", $response1);
$parser = simplexml_load_string($response2);
echo $parser->asXML();
You can use SOAP CLIENT is a good tool for use if you work with Web services. This is easy to use, automaticaly convert your response in SimpleXMLObject and you are able to use XPath to find easy your XML tag.

Parsing response from the WSDL using PHP

I'm very sorry if I made a wrong title, I'm not familiar with SOAP response and types of it. But I guess it's a WSDL response, at least I got it from WSDL link...
I have a following url
http://somedomain.com/j.svc?wsdl
And after I made a request using curl_multi I got the following response. The response was shortened to two results so it would be easier to read
The response is as following:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetJourneyListResponse xmlns="http://tempuri.org/">
<GetJourneyListResult xmlns:a="http://schemas.datacontract.org/2004/07/DreamFlightWCF" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:Journey>
<a:FromAirport>LHR</a:FromAirport>
<a:TotalPrice>146</a:TotalPrice>
</a:Journey>
<a:Journey>
<a:FromAirport>LHR</a:FromAirport>
<a:TotalPrice>155</a:TotalPrice>
</a:Journey>
</GetJourneyListResult>
</GetJourneyListResponse>
</s:Body>
</s:Envelope>
Is there any chance to parse the result using PHP? I made lots of searches including StackOverflow and here what I managed to find.
To parse the above response I can use following code:
$xml = simplexml_load_string($result);
$xml->registerXPathNamespace('flight','http://schemas.datacontract.org/2004/07/DreamFlightWCF');
foreach ($xml->xpath('//flight:Journey') as $item){
print_r($item);
}
It seems that the above PHP code piece is correct by partially. I get the correct amount of "Journey"s but the $item by its own is empty.
Any solutions? Please don't advise to use SoapClient to retrieve the result. I can't move from curl_multi. I already have the result and I need to parse it. Thank you in advance
$soap_request = "<?xml version=\"1.0\"?>\n";
$soap_request .= "<soap:Envelope xmlns:soap=\"http://www.w3.org/2001/12/soap-envelope\" soap:encodingStyle=\"http://www.w3.org/2001/12/soap-encoding\">\n";
$soap_request .= " <soap:Body xmlns:m=\"http://www.example.org/stock\">\n";
$soap_request .= " <m:GetStockPrice>\n";
$soap_request .= " <m:StockName>IBM</m:StockName>\n";
$soap_request .= " </m:GetStockPrice>\n";
$soap_request .= " </soap:Body>\n";
$soap_request .= "</soap:Envelope>";
$header = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: \"run\"",
"Content-length: ".strlen($soap_request),
);
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, "http://ecc6unitst.kaisa.com:8000/sap/bc/srt/wsdl/bndg_386D2B5BD851F337E1000000AC1264E4/wsdl11/allinone/standard/document?sap-client=400" );
curl_setopt($soap_do, CURLOPT_USERPWD, "EBALOBORRP:welcome1");
curl_setopt($soap_do, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($soap_do, CURLOPT_TIMEOUT, 10);
curl_setopt($soap_do, CURLOPT_RETURNTRANSFER, true );
curl_setopt($soap_do, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($soap_do, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($soap_do, CURLOPT_POST, true );
curl_setopt($soap_do, CURLOPT_POSTFIELDS, $soap_request);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, $header);
$str = curl_exec($soap_do);
if(curl_exec($soap_do) === false) {
$err = 'Curl error: ' . curl_error($soap_do);
curl_close($soap_do);
print $err;
} else {
curl_close($soap_do);
var_dump($str);
print 'Operation completed without any errors';
}
First try Parsing SOAP response then try Google.

Categories