<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'];
Related
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();
I need to fetch the value of "joinmeetingurl" element from the xml. I tried in following way. But it returns nothing. Please help me to fetch the value.
<?php
$xml = '<serv:message xmlns:serv="http://www.webex.com/schemas/2002/06/service"
xmlns:com="http://www.webex.com/schemas/2002/06/common"
xmlns:meet="http://www.webex.com/schemas/2002/06/service/meeting"
xmlns:att="http://www.webex.com/schemas/2002/06/service/attendee">
<serv:header>
<serv:response>
<serv:result>SUCCESS</serv:result>
<serv:gsbstatus>PRIMARY</serv:gsbstatus>
</serv:response>
</serv:header>
<serv:body>
<serv:bodycontent xsi:type="meet:getjoinurlMeetingResponse"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<meet:joinmeetingurl>meetingURL</meet:joinmeetingurl>
</serv:bodycontent>
</serv:body>
</serv:message>';
$xml = simplexml_load_string($xml);
$items = $xml->registerXPathNamespace('meet','http://www.webex.com/schemas/2002/06/service/meeting');
$resp = $xml->xpath('//meet:joinmeetingurl');
?>
Im getting empty value for $resp always.
Your XPath should've worked, and you can cast the element to string to get the value, for example :
$xml = <<<XML
<serv:message xmlns:serv="http://www.webex.com/schemas/2002/06/service"
xmlns:com="http://www.webex.com/schemas/2002/06/common"
xmlns:meet="http://www.webex.com/schemas/2002/06/service/meeting"
xmlns:att="http://www.webex.com/schemas/2002/06/service/attendee">
<serv:header>
<serv:response>
<serv:result>SUCCESS</serv:result>
<serv:gsbstatus>PRIMARY</serv:gsbstatus>
</serv:response>
</serv:header>
<serv:body>
<serv:bodycontent xsi:type="meet:getjoinurlMeetingResponse"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<meet:joinmeetingurl>meetingURL</meet:joinmeetingurl>
</serv:bodycontent>
</serv:body>
</serv:message>
XML;
$xml = simplexml_load_string($xml);
$xml->registerXPathNamespace('meet','http://www.webex.com/schemas/2002/06/service/meeting');
$resp = $xml->xpath('//meet:joinmeetingurl');
echo (string)$resp[0];
eval.in demo
output :
meetingURL
Can offer no guidance with simplexml and associated functions but it seems quite simple with standard DOMDocument and DOMXPath
$dom=new DOMDocument;
$dom->loadXML( $xml );
$xpath=new DOMXPath( $dom );
$col=$xpath->query('//meet:joinmeetingurl');
foreach( $col as $node )echo $node->nodeValue;
$dom=null;
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 need to parse the following XML response:
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/"><SOAP:Body><m:LoginResponse xmlns:m="http://www.e-courier.com/schemas/" UserGUID="{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}" UserID="1" LoginGUID=""/></SOAP:Body></SOAP:Envelope>
I need to get the UserGUID, so I created the following peace of code:
$xmlResponse = $client->__doRequest($xml_request, $this->__url_request, "XML", SOAP_1_1);
$xml = simplexml_load_string($xmlResponse);
$xml->registerXPathNamespace('soap', 'http://schemas.xmlsoap.org/soap/envelope/');
$xml->registerXPathNamespace('m', 'http://www.e-courier.com/schemas/');
foreach ($xml->xpath('//LoginResponse') as $a)
{
error_log(print_r($a));
}
The problem is that I never get anything printed on the error_log.
What am I doing wrong?
Edit: I found out that $xml is not being created successfully... Should I use something before calling simplexml_load_string?
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.