I'm trying to parse the xml response of http://api.hostip.info/?ip=12.215.42.19 with SimpleXML but I can't seem to get it work.
Response
<?xml version="1.0" encoding="ISO-8859-1" ?>
<HostipLookupResultSet version="1.0.1" xmlns:gml="http://www.opengis.net/gml" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://www.hostip.info/api/hostip-1.0.1.xsd">
<gml:description>This is the Hostip Lookup Service</gml:description>
<gml:name>hostip</gml:name>
<gml:boundedBy>
<gml:Null>inapplicable</gml:Null>
</gml:boundedBy>
<gml:featureMember>
<Hostip>
<ip>12.215.42.19</ip>
<gml:name>Sugar Grove, IL</gml:name>
<countryName>UNITED STATES</countryName>
<countryAbbrev>US</countryAbbrev>
<!-- Co-ordinates are available as lng,lat -->
<ipLocation>
<gml:pointProperty>
<gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#4326">
<gml:coordinates>-88.4588,41.7696</gml:coordinates>
</gml:Point>
</gml:pointProperty>
</ipLocation>
</Hostip>
</gml:featureMember>
</HostipLookupResultSet>
Can someone help me to access for instance Hostip>ipLocation>pointProperty>Point>coordinates
Thanks in advance!
Here are two ways (which are available elsewhere on SO by searching!).
XPath (a very basic on to demonstrate)
$coords = $xml->xpath('//gml:coordinates');
echo $coords[0];
"Simple" XML (not so simple)
echo $xml
->children('gml', TRUE)->featureMember
->children('', TRUE)->Hostip->ipLocation
->children('gml', TRUE)->pointProperty->Point->coordinates;
You can access attributes like array
http://www.electrictoolbox.com/php-simplexml-element-attributes/
like (im not sure with your example)
Hostip->ipLocation->gml['pointproperty']
Related
I'm trying to parse OTA service's XML response in PHP. I have tried below code but no luck.
$doc = new DOMDocument();
$doc->loadXML($response);
$XMLresults = $doc->getElementsByTagName("OTA_VehAvailRateRS");
I want to get different tags value from xml response. Can someone help me out from this? Thanks. For example i want to parse following xml response:
<?xml version="1.0"?>
<OTA_VehAvailRateRS xmlns="http://www.opentravel.org/OTA/2003/05" TimeStamp="2018-02-28T01:12:27" Target="Test" Version="4.500" SequenceNmbr="1">
<Success/>
<VehAvailRSCore>
<VehRentalCore PickUpDateTime="2018-03-13T08:00:00" ReturnDateTime="2018-03-30T08:00:00">
<PickUpLocation LocationCode="TEST"/>
<ReturnLocation LocationCode="TEST"/>
</VehRentalCore>
<VehVendorAvails>
<VehVendorAvail>
<VehAvails> <VehAvail>
<VehAvailCore Status="Available">
<Vehicle Code="TEST15" VendorCarType="TEST15" Description="TEST"/>
<RentalRate>
<RateDistance Unlimited="True" DistUnitName="Mile" VehiclePeriodUnitName="RentalPeriod"/>
<VehicleCharges>
<VehicleCharge Description="TEST" Amount="1299.35" CurrencyCode="" GuaranteedInd="True" Purpose="1"> <Calculation UnitCharge="33.32" UnitName="Hour"/>
<Calculation UnitCharge="1560.00" UnitName="Month"/>
<Calculation UnitCharge="499.75" UnitName="Week"/>
<Calculation UnitCharge="99.95" UnitName="Day"/>
<TaxAmounts> </TaxAmounts>
</VehicleCharge>
</VehicleCharges>
</RentalRate>
<Fees> </Fees>
<TotalCharge CurrencyCode="" RateTotalAmount="1299.35" EstimatedTotalAmount="1299.35"/>
<PricedEquips> </PricedEquips> </VehAvailCore> <VehAvailInfo> <PricedCoverages> </PricedCoverages> </VehAvailInfo> </VehAvail> </VehAvails> </VehVendorAvail> </VehVendorAvails> </VehAvailRSCore> </OTA_VehAvailRateRS>
I have found solution. I have used simplexml_load_string() function for parse response. For ex:
$xml = simplexml_load_string($finalresponse);
var_dump($xml); //getting parsed response here
For getting value of different xml nodes i have used below code:
$nodevalue = $xml->VehAvailRSCore->VehRentalCore->attributes()->PickUpDateTime; //this code gives me "2018-03-13T08:00:00" as result
I am parsing through the following XML file:
testxml.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?><document>
<node id="n0">
<data key="d6">
<y:GenericNode configuration="TEXT I WANT TO GET">
<y:Geometry height="56.030557066666574" width="181.68810666666667" x="638.4599149206349" y="143.24969103333325"/>
<y:Fill color="#FFCC66" color2="#FF9900" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="node_width" configuration="CroppingLabel" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="34.265625" horizontalTextPosition="center" iconTextGap="4" modelName="custom" textColor="#000000" verticalTextPosition="bottom" visible="true" width="181.68810666666667" x="0.0" y="10.882466033333287">Text I want to Get<y:LabelModel>
<y:SmartNodeLabelModel distance="4.0"/>
</y:LabelModel>
<y:ModelParameter>
<y:SmartNodeLabelModelParameter labelRatioX="-0.5" labelRatioY="0.0" nodeRatioX="-0.5" nodeRatioY="0.0" offsetX="0.0" offsetY="0.0" upX="0.0" upY="-1.0"/>
</y:ModelParameter>
</y:NodeLabel>
</y:GenericNode>
</data>
</node>
I am interested in only a handful of attributes, namely the node id, data key which I am able to get with the code below. However, when I move into the y: namespace I get nothing.
xmlparser.php
<?php
$xml = simplexml_load_file("testxml.xml")
or die("Error: Cannot create object - check that the XML file exists and is
not corrupted"); print_r($xml);
echo $xml->node[0]['id']; // This works
echo $xml->node[0]->data[0]['key']; // This works
echo $xml->children('y', true)->GenericNode->attributes()->configuration; // Nothing
echo $xml->children('y', true)->GenericNode->NodeLabel; // Nothing
?>
I've read through previous answers on similar issues, based on which I adopted the children approach. However I can't get this to work, and I have no idea how to implement some of the other approaches such as declaring namespaces and the xpath approach.
Any help would be greatly appreciated.
That's because y:GenericNode isn't direct child of the root element, so you shouldn't be accessing it directly from $xml :
$xml->node->data->children('y', true)->GenericNode->attributes()->configuration;
quick test : https://eval.in/761412
I am trying to read the value for 3 specific XML nodes (bill_codes, sent_total, clicked_unique_total) I have done a lot of testing and I feel like I need someone with fresh eyes to look at this and help me find out what I no longer see..
I am using the simplexml_load_string function to load the XML into an array..
Here is the code that I have so far:
$xml = simplexml_load_string($content);
echo $xml->methodResponse->item->responseData->message_data->message->bill_codes;
This is the XML that I am using (comes from an API Call so I have no access to modifying/updating the structure of the XML)
<?xml version="1.0" encoding="utf-8"?>
<methodResponse>
<item>
<methodName>
<![CDATA[legacy.message_stats]]>
</methodName>
<responseData>
<message_data>
<message id="2345456">
<message_subject>
<![CDATA[#1 Item You Should Be Hoarding in 2015]]>
</message_subject>
<date_sent>2014-12-18 04:01:34</date_sent>
<message_notes>
<![CDATA[Sample Notes]]>
</message_notes>
<withheld_total>0</withheld_total>
<globally_suppressed>0</globally_suppressed>
<suppressed_total>0</suppressed_total>
<bill_codes>
<![CDATA[8578]]>
</bill_codes>
<sent_total>734273</sent_total>
<link_append_statement/>
<timezone/>
<message_name>
<![CDATA[Sample Message Name]]>
</message_name>
<optout_total>4054</optout_total>
<optout_rate_total>0.55</optout_rate_total>
<clicked_total>5363</clicked_total>
<clicked_unique>4350</clicked_unique>
<clicked_rate_unique>13.71</clicked_rate_unique>
<campaign_id>228640</campaign_id>
<campaign_type>C</campaign_type>
<included_groups>
<segment id="1208891">
<![CDATA[Segment Name Here]]>
</segment>
</included_groups>
<included_smartlists></included_smartlists>
<excluded_groups></excluded_groups>
<excluded_smartlists></excluded_smartlists>
<attributes></attributes>
<link id="40278272">
<has_name>1</has_name>
<clicked_unique_total>4350</clicked_unique_total>
</link>
</message>
</message_data>
</responseData>
<responseNum>
<![CDATA[1]]>
</responseNum>
<responseCode>
<![CDATA[201]]>
</responseCode>
</item>
</methodResponse>
No need to include the parent, just start with the ->item:
echo $xml->item->responseData->message_data->message->bill_codes;
Sample Output
I am using simplexml_load_string in order to attempt to turn my XML file into variables I can later enter into a database however am struggling with the output working in some instances and not in others.
The xml
$response ='<ndxml version="2.0">
<status code="OK">
<response function="createNewJob" id="1">
<status code="OK">
<job uniqueref="5830z858279" jobref="858279">
<consignment number="8613030">
<reference>16755</reference>
<deadlinedatetime date="2014-01-16" time="17:30:00">
<jobnumber>
<labeldata styletag="APC">
<shippingdate date="15/01/2014">
<addresses>
<address type="COLLECTION">
<company>UK Stuff and Things</company>
</address>
<address type="DELIVERY">
<contact>Person</contact>
<telephone>02089636985</telephone>
<addresslines>
<addressline number="1">Daffy</addressline>
<addressline number="2">Things</addressline>
<addressline number="3">Places</addressline>
<addressline number="4">NORTHAMPTONSHIRE</addressline>
</addresslines>
<postzip>NB12 1ER</postzip>
<country isocode="GB">United Kingdom</country>
</address>
</addresses>
<notes>
<account code="21171">
<tariff code="MP16">
<routing>
<delivery>
<route>LOCAL</route>
<zone>B</zone>
<driver>31</driver>
<serviceoptions>
</serviceoptions></delivery>
<depots>
<depot number="211" type="Sending">
<depot number="211" type="Request">
<depot number="211" type="Delivery">
</depot></depot></depot></depots>
</routing>
<parcels total="1">
<dimensions height="0" width="0" length="0">
<volweight>0.0</volweight>
<weight>0.14</weight>
<parcel number="1">
<barcode>21163148613030001</barcode>
</parcel>
</dimensions></parcels>
</tariff></account></notes></shippingdate></labeldata>
</jobnumber></deadlinedatetime></consignment></job>
</status>
</response>
So I have managed to successfully grab certain elements from this by using the recommended code on the documentation:
$parsed=simplexml_load_string($response);
$response_statuscode = $parsed->status['code'];
$response_statuscode2 = $parsed->response->status['code'];
$response_consignment_num = $parsed->response->job->consignment['number'];
$response_reference = $parsed->response->job->reference;
All of these have worked exactly as required, however from there it all goes a bit wrong for me. Things with more complicated attributes (more than one!) just don't seem to be working for me.
$response_date = $parsed->response->job->deadlinedatetime['date'];
I also tried:
$parsed->response->job->deadlinedatetime->attributes()->date;
And from there on I can't seem to process anything from label data properly. I am just making a mess of my understanding of the tree?
$response_account_code = $parsed->response->job->labeldata->account['code'];
As always, thanks in advance!
There's a very common approach to handle situations like this one:
Since simplexml_load_string() returns an object and since object property names cannot contain spaces, it would make sense to recursively convert an object into array.
You can use this function to do that:
function object2array($object) {
return json_decode(json_encode($object), true);
}
$parsed = simplexml_load_string($response);
// Now, recursively convert it into an array
$parsed = object2array($parsed);
// Now you can access its values by keys, like this:
$parsed['response']['job']['labeldata']['account'];
As for dumping, you can simply do print_r($parsed)
I am sending array of objects in XML Soap response from my java code to php in my project using WSDL.
I want to store values in php for my project.
I tried many ways but couldn't able to find how to parse my xml and read values. I am not export in xml area.
Please anyone help me for read my values from values.
My SOAP Response Body:
<soapenv:envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" \xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:body>
<getactualtimerequestresponse xmlns="http://impl.sample.com">
<getactualtimereturn>.
<ns1:projectlist xmlns:ns1="http://response.sample.com">
<item>
<ns2:userid xmlns:ns2="http://request.sample.com">4</ns2:userid>
<ns3:username xmlns:ns3="http://request.sample.com">Manoj Arun</ns3:username>
</item>
<item>
<ns5:userid xmlns:ns5="http://request.sample.com">5</ns5:userid>
<ns6:username xmlns:ns6="http://request.sample.com">Sethu Raman</ns6:username>
</item>
</ns1:projectlist>
<ns10:message xsi:nil="true" xmlns:ns10="http://response.sample.com"></ns10:message>
</getactualtimereturn>
</getactualtimerequestresponse>
</soapenv:body>
</soapenv:envelope>
projectList is my object created in java.
In PHP:
I tried to read like below but i didn't got anything.
foreach($xml->xpath('//ns:projectList') as $header)
{
foreach($header->item as $userIds)
{
echo $userIds->xpath('//ns:userId');
}
}
Thanks in advance...
$client = new SoapClient('http://url.com?wsdl');
$params = array(Java arg => php value);
$result = $client->Function( $parms );
print_r($result);