Can't parse xml from curl response - php

I use the code below to get xml data from some API:
<?php
$ch = curl_init();
$xml = '<?xml version="1.0" encoding="utf-8"><file><auth>myapikey</auth><warenhouse/></file>';
curl_setopt($ch, CURLOPT_URL, 'http://somesite.com/xml.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, Array("Content-Type: text/xml"));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
?>
I get xml data successfully something like
<?xml version="1.0" encoding="UTF-8"?>
<response>
<responseCode>200</responseCode>
<result>
<whs>
<warenhouse>
<city>New York City</city>
<address>Some Address</address>
<number>1</number>
<phone>1111111</phone>
</warenhouse>
<warenhouse>
...
</warenhouse>
</whs>
</result>
</response>
</xml>
but I can't parse and echo only cities using
$parser = simplexml_load_string($response);
foreach($parser->warenhouse as $item) {
echo $item->city;
}
What's wrong?

Your XML is a bit malformed , remove that </xml> from the end.
You need to loop like this
foreach ($xml->result->whs->warenhouse as $child)
{
echo $child->city;
}
The code..
<?php
$xml= <<<XML
<?xml version="1.0" encoding="UTF-8" ?>
<response>
<responseCode>200</responseCode>
<result>
<whs>
<warenhouse>
<city>New York City</city>
<address>Some Address</address>
<number>1</number>
<phone>1111111</phone>
</warenhouse>
<warenhouse>
</warenhouse>
</whs>
</result>
</response>
XML;
$xml = simplexml_load_string($xml);
foreach ($xml->result->whs->warenhouse as $child)
{
echo $child->city;
}
OUTPUT:
New York City
Demo

Related

Get a value from SOAP response from multiple xml data using PHP

This is the response of the soap request.
<?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>
<GetConfigurationInfoResponse xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://micros-hosting.com/EGateway/">
<configInfoResponse>
<OperationalResult>
<Success>true</Success>
<ErrorCode>Success</ErrorCode>
<ErrorMessage>Success</ErrorMessage>
</OperationalResult>
<ConfigInfoType>
<EConfigurationInfoType>MENUITEMDEFINITIONS</EConfigurationInfoType>
</ConfigInfoType>
**<MenuItemDefinitions><?xml version="1.0" encoding="utf-8"?><?micros-type Micros.PosCore.DataStore.DbRecords.DbMenuItemDefinition[], PosCore, Version=2.5.0.0, Culture=neutral, PublicKeyToken=null?><ArrayOfDbMenuItemDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><DbMenuItemDefinition><NameOptions>0000000</NameOptions><MenuItemDefID>4055</MenuItemDefID><HierStrucID>25</HierStrucID><MenuItemMasterID>1570</MenuItemMasterID><SequenceNum>1</SequenceNum><Name1><StringNumberId>8507</StringNumberId><StringText>=Breakfast=</StringText></Name1><Name2><StringNumberId>8508</StringNumberId><StringText /></Name2><SluSort>0</SluSort><NluNumber>0</NluNumber><Tare>0</Tare><Surcharge>0</Surcharge><IconNumber>0</IconNumber><OptionBits>00000000</OptionBits><SpecialCount>0</SpecialCount><PrepTime>0</PrepTime><Name3><StringNumberId>0</StringNumberId><StringText /></Name3><LongDescriptor><StringNumberId>0</StringNumberId><StringText /></LongDescriptor><MenuItemClassObjNum>0</MenuItemClassObjNum><NluGroupIndex>0</NluGroupIndex><SluIndex>0</SluIndex><HhtSluIndex>0</HhtSluIndex><MainLevels>00000000</MainLevels><SubLevels>00000000</SubLevels><PosRef>0</PosRef><PrintClassObjNum>0</PrintClassObjNum><PrefixLevelOverride>0</PrefixLevelOverride><GuestCount>0</GuestCount><MenuLevelEntries /><DefaultCondiments /><NextScreen /><MiMasterObjNum>10010000</MiMasterObjNum><CheckAvailability>false</CheckAvailability><OutOfMenuItem>false</OutOfMenuItem></DbMenuItemDefinition><DbMenuItemDefinition;</ArrayOfDbMenuItemDefinition></MenuItemDefinitions>**
</configInfoResponse>
</GetConfigurationInfoResponse>
</soap:Body>
</soap:Envelope>
How can I get value from this <MenuItemDefinitions></MenuItemDefinitions>? This xml element inside another XML data. How to say this kind of XML?
How to filter that value using PHP? I only need get value from the inside <MenuItemDefinitions></MenuItemDefinitions> xml value.
This is the soap request php code.
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://192.168.5.10:8080/EGateway/SimphonyPosApiWeb.asmx");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, "<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soap:Body>
<GetConfigurationInfo>
<vendorCode />
<employeeObjectNum>10009</employeeObjectNum>
<configurationInfoType>
<int>1</int>
</configurationInfoType>
<revenueCenter>5</revenueCenter>
<configInfoResponse />
</GetConfigurationInfo>
</soap:Body>
</soap:Envelope>");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type: text/xml;",
"SOAPAction: http://192.168.5.10:8080/EGateway/GetConfigurationInfo"
));
$response = curl_exec($ch);
curl_close($ch);
var_dump($response);

print xml response separately for each property

I am trying to convert this XML to array this is the response I am getting from API and I want to get the value of statuscode but I am unable to do it.
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
but when i am using the following code
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'RequestData='.$post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
$resultres=xml2ary($result);
echo '<pre>';
print_r($resultres);
The output is
Array
(
[string] => Array
(
[_a] => Array
(
[xmlns] => http://tempuri.org/
)
[_v] => 201234
)
)
How is the result changing? I have used one more technique also but with that also I am not getting the result that is required
Have a look at SimpleXML
<?php
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'RequestData='.$post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
/** #var SimpleXMLElement $xml */
$xml = simplexml_load_string($result);
// nice, use SimpleXMLElement object
var_dump($xml);
// not nice, use array instead
var_dump((array) $xml);
Just make sure the XML response you're getting from the API is the same you have posted above. Here it is again for reference:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
Here is an example without cURL, just add it to a file and run it from the terminal:
<?php
$xmlString = <<<XML
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
XML;
$xml = simplexml_load_string($xmlString);
// everything
var_dump($xml);
// independent values
var_dump((string) $xml->STATUSCODE);
var_dump((string) $xml->STATUS);
// now with arrays
$array = (array) $xml;
// everything
var_dump($array);
// independent values
var_dump($array['STATUSCODE']);
var_dump($array['STATUS']);
// want to print it?
echo sprintf('Registration responded with status code %d and status %d', $xml->STATUSCODE, $xml->STATUS) . PHP_EOL;
echo sprintf('Registration responded with status code %d and status %d', $array['STATUSCODE'], $array['STATUS']) . PHP_EOL;
If the XML is coming through, for instance like so:
<class>
<type>
<input>Text</input>
<input>Text</input>
</type>
<type>
<input>Text</input>
<input>Text</input>
</type>
<type>
<input>Text</input>
<input>Text</input>
</type>
</class>
What you could do is:
$xml = simplexml_load_file("filepath");
$classes = $xml->$class;
foreach ($classes as $keyClass => $class) {
echo "<ul><li>Class</li><ul>";
$types = $class->type;
foreach ($types as $keyType => $type) {
echo "<li>Type</li><ul>";
$inputs = $type->input;
foreach ($inputs as $keyInput => $input) {
echo "<li>Input</li>";
}
echo "</ul>";
}
echo "</ul></ul>";
}

PHP - SOAP response to JSON

I am trying to parse SOAP response to JSON. So far I have this code:
$data = '<?xml version="1.0" encoding="utf-8"?>';
$data .= '<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">';
$data .= '<soap12:Body>';
$data .= '<GetCommunities xmlns="url">';
$data .= '<APIUsername>string</APIUsername>';
$data .= '<APIPassword>string</APIPassword>';
$data .= '</GetCommunities>';
$data .= '</soap12:Body>';
$data .= '</soap12:Envelope>';
$soap_do = curl_init();
curl_setopt($soap_do, CURLOPT_URL, "url" );
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, $data);
curl_setopt($soap_do, CURLOPT_HTTPHEADER, array('Content-Type: text/xml; charset=utf-8', 'Content-Length: '.strlen($data) ));
$result = curl_exec($soap_do);
echo $result;
This code is working and I am getting following result:
<?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>
<GetCommunitiesResponse xmlns="url">
<GetCommunitiesResult>
<Communities>
<CommunityID>1</CommunityID>
<CommunityName> Not Specified</CommunityName>
</Communities>
<Communities>
<CommunityID>276</CommunityID>
<CommunityName>Bella Toscana</CommunityName>
</Communities>
<Communities>
<CommunityID>31</CommunityID>
<CommunityName>Crescent Lakes</CommunityName>
</Communities>
<Communities>
<CommunityID>62</CommunityID>
<CommunityName>Hillcrest Estate</CommunityName>
</Communities>
<Communities>
<CommunityID>750</CommunityID>
<CommunityName>Sunny Beach</CommunityName>
</Communities>
<Communities>
<CommunityID>124</CommunityID>
<CommunityName>Terra Verde Resort</CommunityName>
</Communities>
<Communities>
<CommunityID>744</CommunityID>
<CommunityName>The Dales at West Haven</CommunityName>
</Communities>
<Communities>
<CommunityID>158</CommunityID>
<CommunityName>Westridge</CommunityName>
</Communities>
</GetCommunitiesResult>
</GetCommunitiesResponse>
</soap:Body>
</soap:Envelope>
I need to create JSON response from the data which can be found between GetCommunitiesResult tags. How can I do this?
Edited and tested
// a bit of a hack, but let's see...
list($trash,$result)=explode('<soap:Body>',$result);
list($result,$trash)=explode('</soap:Body>',$result);
unset($trash);
$result=str_replace('xmlns="url"','',$result);
$simple_result=simplexml_load_string($result);
$json_result=json_encode($simple_result);
//var_export($simple_result);
echo $json_result;
Output:
{"GetCommunitiesResult":{"Communities":[{"CommunityID":"1","CommunityName":"
Not Specified"},{"CommunityID":"276","CommunityName":"Bella
Toscana"},{"CommunityID":"31","CommunityName":"Crescent
Lakes"},{"CommunityID":"62","CommunityName":"Hillcrest
Estate"},{"CommunityID":"750","CommunityName":"Sunny
Beach"},{"CommunityID":"124","CommunityName":"Terra Verde
Resort"},{"CommunityID":"744","CommunityName":"The Dales at West
Haven"},{"CommunityID":"158","CommunityName":"Westridge"}]}}

<request> <action>getCategories</action> <params />

I got this code and I need to write additional code to make it work:
<ul>
<li>1</li>
<li>2</li>
</ul>
<hr>
<?php
$iTest = (int) $_GET['test'];
$sXML = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
switch ($iTest) {
case 1:
$sXML .= '<request>
<action>getCategories</action>
<params />
</request>';
break;
case 2:
$sXML .= '<request>
<action>getProducts</action>
<params>
<catid>1</catid>
<page>1</page>
</params>
</request>';
break;
default:
exit();
break;
}
I actually understand what it should do but I need to write an input file that would do something according to the action send, how should I treat this :
<request>
<action>getProducts</action>
<params>
<catid>1</catid>
<page>1</page>
</params>
</request>
if it would be just a simple variable everything would be ok but now I dont get how to get around it
whats here is all clear to me, just send sXML to input and return result:
$oCurl = curl_init();
curl_setopt($oCurl, CURLOPT_URL, 'http://localhost/joboffer/input.php');
curl_setopt($oCurl, CURLOPT_POST, true);
curl_setopt($oCurl, CURLOPT_POSTFIELDS, $sXML);
curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($oCurl, CURLOPT_FRESH_CONNECT, true);
curl_setopt($oCurl, CURLOPT_HTTPHEADER,
array(
'Content-type: text/xml; charset=UTF-8',
'Expect: '
)
);
$sRespond = curl_exec($oCurl);
$iRespondCode = curl_getinfo($oCurl, CURLINFO_HTTP_CODE);
curl_close($oCurl);
echo '<pre>RESPOND ', $iRespondCode, "\n\n", htmlentities($sRespond);

how to show the data of an xml in a datatable using php

Below is the xml I am getting from as response from REST webservice call in a php method
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<products>
<capacity>1</capacity>
<id>ae123</id>
<group>Per</group>
<name>xxxx</name>
</products>
<records>1
</records>
</response>
My php method which calls the webservice and getting the xml data is
function getAjaxProducts(){
$path="my webservice url";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$retValue = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($httpCode>400) {
$retValue="<error><errorcode>".$httpCode."</errorcode></error>";
echo $retValue;
}
curl_close($ch);
echo $retValue;
}
$retValue contains the xml file.
I am totally new to php and don't know as to how I can show the product details in a datatable from the xml.
Any idea regarding this?
simplexml_load_string() should do the trick
$retValue = '<response>
<products>
<capacity>1</capacity>
<id>ae123</id>
<group>Per</group>
<name>xxxx</name>
</products>
<records>1
</records>
</response>';
$xml = simplexml_load_string($retValue);
echo $xml->products->capacity . "<br>\n";
echo $xml->products->group . "<br>\n";
echo $xml->products->name . "<br>\n";
echo $xml->records . "<br>\n";
See it in action

Categories