I am calling a web service using SoapClient and attempting to pull data from the response output. I have modified the Soap response so that it displays in XML.
I did so by writing this: $resultxml = htmlentities($client->__getLastResponse()) . "\n";.
If you do a simple print_r($resultxml); you receive the full output, obviously.
What I am having trouble with is using DomDocument with $resultxml to create my techData array. If I copy and paste the Soap output and create a stand-alone XML file with it, then add it to $dom->loadXML(); the techData array is created perfectly. However, when I try to pull the XML from $resultxml I receive a blank array.
Any ideas as to why this is? Should I consider revising $resultxml = htmlentities($client->__getLastResponse()) . "\n";? Am I calling it incorrectly?
Thanks so much.
My PHP with my SoapClient request and array code:
<?php
$client = new SoapClient('http://services.chromedata.com/Description/7b?wsdl', array('trace' => 1));
$account = ['number'=>"", 'secret'=>"", 'country'=>"US", 'language'=>"en"];
$switch = ["ShowAvailableEquipment", "ShowExtendedTechnicalSpecifications", "ShowExtendedDescriptions"];
$vin = $_POST["b12"];
$result = $client->describeVehicle([
'accountInfo' => $account,
'switch' => $switch,
'vin' => $vin
]);
$resultxml = htmlentities($client->__getLastResponse()) . "\n";
$dom = new DOMDocument();
$dom->loadXML($resultxml);
$techData = [];
foreach ( $dom->getElementsByTagName('technicalSpecification') as $techSpec ) {
$id = $techSpec->getElementsByTagName('titleId')->item(0)->nodeValue;
$techData [$id]= $techSpec->getElementsByTagName('value')->item(0)->getAttribute("value")."<br>";
}
print_r($techData);
echo "<br>";
When you use htmlentities() - this will encode the markup, so
<S:Body>
becomes
<S:Body>
thiw ill not work if you then try to load it as an XML document, so just use
$resultxml = $client->__getLastResponse();
Related
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
<GetCategoriesJsonResponse xmlns="http://tempuri.org/">
<GetCategoriesJsonResult>[{"code":"0","description":"Sides","storeNumber":"3733"},{"code":"1","description":"Sandwiches","storeNumber":"3733"},</GetCategoriesJsonResult>
</GetCategoriesJsonResponse>
</s:Body>
</s:Envelope>
That is the result of the API, but I want to convert it like:
[
{
"code": "0",
"description": "Sides",
"storeNumber": "3733"
},
{
"code": "1",
"description": "Sandwiches",
"storeNumber": "3733"
},
]
How can I do this? I've tried json_encode and json_decode but it didn't work for me. I have applied different methods to convert it but it's still showing XML results. Can anyone tell me how I can convert it into JSON?
Here's a good answer on available options to working with xml https://stackoverflow.com/a/3577662/3266626
I use FluentDom
$xml = file_get_contents("xml_file.xml");
$doc = new DOMDocument();
$doc->loadXML($xml);
$json = new \FluentDOM\Serializer\Json\RabbitFish($doc);
$object = json_decode($json);
echo "<pre>" . print_r( $object, true) . "</pre>";
echo "<script>console.log({$json})</script>";
Edit: replaced
// PHP Deprecated: Non-static method DOMDocument::loadXML() should not be called statically
$doc = DOMDocument::loadXML($xml);
with
$doc = new DOMDocument();
$doc->loadXML($xml);
I found the solution on that link thanks guys for helping
using api response in this way helps me alot
How to convert SOAP response to PHP Array?
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $response);
$xml = new SimpleXMLElement($response);
$body = $xml->xpath('//sBody')[0];
$array = json_decode(json_encode((array)$body), TRUE);
This code is perfectly done thing into JSON
First parse xml and convert data to array:
$xml=(array)simplexml_load_string($myXMLData);
$json_output = $xml['GetCategoriesJsonResult'];
Im new to xml and i just want to pass an object to url and parse it to array . dont know what to do.
Here's my code:
$xml = "<user><name>".$name."</name><balance>".$balance."</balance><address>".$address."</address><mobile>".$mobile."</mobile></user>";
$simple = new SimpleXMLElement($xml);
$simple2 = $simple->asXML();
$sample = simplexml_load_string($simple2);
$url = $GLOBALS['urlPath'].'webportal_sqlanywhere/xml.php?id='.$(my xml);
$path_file = file_get_contents($url);
echo $path_file;
I have the following response from a XML api , I want to display the text that is placed in the comments section .
<OTA_AirDetailsRS PrimaryLangID="eng" Version="1.0" TransactionIdentifier=""><Errors><Error Type="ERR" FLSErrorCode="-10" FLSErrorName="Invalid Input"/></Errors><!-- Reason for error: The Date parameter is not valid [2014-05-16] --></OTA_AirDetailsRS>
I have used this :
...
$query = curl_exec($curl_handle);
curl_close($curl_handle);
$xml = new SimpleXmlElement($query);
if($xml->Errors){
$doc = new DOMDocument;
$doc->loadXML($xml);
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//comment()') as $comment)
{
var_dump($comment->textContent);
}
Its not displaying anything in this case , but if instead of passing xml response , I pass it a simple xml in string format , it is working . Please suggest if something is wrong.
You need to load the XML, not the object from your SimpleXmlElement call:
$doc = new DOMDocument;
$doc->loadXML($query);
Then your script outputs:
string(64) " Reason for error: The Date parameter is not valid [2014-05-16] "
I have an XML string that I have built up using the following example:
//add root
$Add = $dom->appendChild($dom->createElement('Add'));
//pCase
$pCase = $Add->appendChild($dom->createElement('pCase'));
//add elements
$LeadGenID = $pCase->appendChild($dom->createElement('LeadGenID'));
$LeadGenID->appendChild($dom->createTextNode('22'));
$Debtor = $pCase->appendChild($dom->createElement('Debtor'));
//address fields
$Addresses = $Debtor->appendChild($dom->createElement('Addresses'));
$Address = $Addresses->appendChild($dom->createElement('Address'));
//array of address objects should go here
$test1 = $dom->saveXML();
$sxe = simplexml_load_string($test1);
if ($sxe === false) {
echo 'Error while parsing the document';
exit;
}
$dom_sxe = dom_import_simplexml($sxe);
if (!$dom_sxe) {
echo 'Error while converting XML';
exit;
}
$dom = new DOMDocument('1.0', 'utf-8');
$dom_sxe = $dom->importNode($dom_sxe, true);
$dom_sxe = $dom->appendChild($dom_sxe);
echo $dom->save('application.xml');
This then outputs the following in my XML:
<Add>
<pCase>
<LeadGenID>22</LeadGenID>
<Debtor>
<Addresses><Address/></Addresses>
</Debtor>
</pCase>
I also need to output an array into this XML, so that the full output is as follows:
<Add>
<pCase>
<LeadGenID>22</LeadGenID>
<Debtor>
<Addresses>
<Address>
<Street>Some street</Street>
<Postcode>Some postcode</Postcode>
</Address>
</Addresses>
</Debtor>
</pCase>
I have tried to accomplish this using
$address_array = array (
$_POST['Street'] => 'Street',
$_POST['Postcode'] => 'Postcode'
);
$xml = new SimpleXMLElement('<Address/>');
array_walk_recursive($address_array, array ($xml, 'addChild'));
but at this point I am completely lost. The API I have been given is sparse on documentation to say the least but I'm getting closer with it, but I need to enter the address as an array for the gateway. I am new to PHP as I am primarily a frontend developer who has usually only done simple contact forms etc in PHP.
How can I output the XML example I've given above?
Thanks
Random weird stuff I've spot:
You start with new SimpleXMLElement('<Address/>') but your root node is <Addresses>
An $Address variable pops up from nowhere
A $dom object pops up from nowhere
You call createTextNode() which:
It isn't a SimpleXML method but a DOMDocument method
Expects a string as argument but it's fed with a SimpleXMLElement instance
Creates a text node
Have a look at http://www.lalit.org/lab/convert-php-array-to-xml-with-attributes/
It is a very small and simple to use library, if you just need array to xml.
A web service return Xml of format
<string>
<NewDataSet>
<DealBlotter>
<CustomerReference>161403239</CustomerReference>
<Symbol>EUR/USD</Symbol>
<BuySell>S</BuySell>
<ContractValue>-100000</ContractValue>
<Price>1.35070</Price>
<CounterValue>-135070</CounterValue>
<TradeDate>2011-01-20 22:05:21.690</TradeDate>
<ConfirmationNumber>78967117</ConfirmationNumber>
<Status>C</Status>
<lTID>111913820</lTID>
</DealBlotter>
</NewDataSet>
</string>
Now i am using curl to access this and then -
$xml = simplexml_load_string($result);
$dom = new DOMDOcument();
// Load your XML as a string
$dom->loadXML($xml);
// Create new XPath object
$xpath = new DOMXpath($dom);
$res = $xpath->query("/NewDataSet/DealBlotter");
foreach($res as $node)
{
print "i went inside foreach";
$custref = ($node->getElementsByTagName("CustomerReference")->item(0)->nodeValue);
print $custref;
$ccy = ($node->getElementsByTagName("Symbol")->item(0)->nodeValue);
print $ccy;
$type = ($node->getElementsByTagName("BuySell")->item(0)->nodeValue);
$lots = ($node->getElementsByTagName("ContractValue")->item(0)->nodeValue);
$price = ($node->getElementsByTagName("Price")->item(0)->nodeValue);
$confnumber = ($node->getElementsByTagName("ConfirmationNumber")->item(0)->nodeValue);
$status = ($node->getElementsByTagName("Status")->item(0)->nodeValue);
$ltid = ($node->getElementsByTagName("lTID")->item(0)->nodeValue);
$time = ($node->getElementsByTagName("TradeDate")->item(0)->nodeValue);
}
But nothing is getting printed. except the dummy statement.
using $res = $xpath->query("/string/NewDataSet/DealBlotter"); did not help. Also a print_r($res); gives output as DOMNodeList obect.
Doing this also does not print anything
$objDOM = new DOMDocument();
$objDOM->load($result);
$note = $objDOM->getElementsByTagName("DealBlotter");
foreach( $note as $value )
{
print "hello";
$tasks = $value->getElementsByTagName("Symbol");
$task = (string)$tasks->item(0)->nodeValue;
$details = $value->getElementsByTagName("Status");
$detail = (string)$details->item(0)->nodeValue;
print "$task :: $detail <br>";
}
There are a few problems.
With how you're loading the xml. Get rid of the simplexml line. It's not needed, and is messing things up. Instead just do $dom->loadXml($result);. There's no reason to load SimpleXML first if you're going to pass it directly into DomDocument.
With your query, the / operator is the direct decendent operator. So it means directly next to. So your first tag should be the root. So either add the root onto it:
$res = $xpath->query("/string/NewDataSet/DealBlotter");
Or make the leading slash into // which selects any matching decendent:
$res = $xpath->query("//NewDataSet/DealBlotter");
And finally, doing a var_dump on $res isn't going to tell you much. Instead, I like to do var_dump($res->length) since it'll tell you how many matches it has rather than that it's a domnodelist (which you already know)...