Parse last item XML PHP using xpath (Russian Post tracking API) - php

I have some difficult parsing the last element (ns3:Name and
ns3:OperDate) from Russian post tracking API using PHP.
Tried a few xpath queries without success.
Any help will be appreciated.
Here is example of the XML:
<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://www.w3.org/2003/05/soap-envelope">
<S:Body>
<ns7:getOperationHistoryResponse xmlns:ns7="http://russianpost.org/operationhistory" xmlns:ns2="http://russianpost.org/sms-info/data" xmlns:ns3="http://russianpost.org/operationhistory/data" xmlns:ns4="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns5="http://www.russianpost.org/custom-duty-info/data" xmlns:ns6="http://www.russianpost.org/RTM/DataExchangeESPP/Data">
<ns3:OperationHistoryData>
<ns3:historyRecord>
<ns3:AddressParameters>
<ns3:OperationAddress>
<ns3:Index>102976</ns3:Index>
<ns3:Description>MR LC Vnukovo Cex-1</ns3:Description>
</ns3:OperationAddress>
<ns3:CountryFrom>
<ns3:Id>643</ns3:Id>
<ns3:Code2A>RU</ns3:Code2A>
<ns3:Code3A>RUS</ns3:Code3A>
<ns3:NameRU>?????????? ?????????</ns3:NameRU>
<ns3:NameEN>Russian Federation</ns3:NameEN>
</ns3:CountryFrom>
<ns3:CountryOper>
<ns3:Id>643</ns3:Id>
<ns3:Code2A>RU</ns3:Code2A>
<ns3:Code3A>RUS</ns3:Code3A>
<ns3:NameRU>?????????? ?????????</ns3:NameRU>
<ns3:NameEN>Russian Federation</ns3:NameEN>
</ns3:CountryOper>
</ns3:AddressParameters>
<ns3:FinanceParameters>
<ns3:Payment>0</ns3:Payment>
<ns3:Value>0</ns3:Value>
<ns3:MassRate>0</ns3:MassRate>
<ns3:InsrRate>0</ns3:InsrRate>
<ns3:AirRate>0</ns3:AirRate>
<ns3:Rate>0</ns3:Rate>
<ns3:CustomDuty>0</ns3:CustomDuty>
</ns3:FinanceParameters>
<ns3:ItemParameters>
<ns3:Barcode>RB842972220RU</ns3:Barcode>
<ns3:ValidRuType>false</ns3:ValidRuType>
<ns3:ValidEnType>false</ns3:ValidEnType>
<ns3:ComplexItemName>Small packet registered</ns3:ComplexItemName>
<ns3:MailType>
<ns3:Id>5</ns3:Id>
<ns3:Name>Small packet</ns3:Name>
</ns3:MailType>
<ns3:MailCtg>
<ns3:Id>1</ns3:Id>
<ns3:Name>Registered</ns3:Name>
</ns3:MailCtg>
<ns3:Mass>0</ns3:Mass>
</ns3:ItemParameters>
<ns3:OperationParameters>
<ns3:OperType>
<ns3:Id>8</ns3:Id>
<ns3:Name>Processing</ns3:Name>
</ns3:OperType>
<ns3:OperAttr>
<ns3:Id>0</ns3:Id>
<ns3:Name>Sorting</ns3:Name>
</ns3:OperAttr>
<ns3:OperDate>2016-12-20T22:56:13.000+03:00</ns3:OperDate>
</ns3:OperationParameters>
<ns3:UserParameters>
<ns3:SendCtg>
<ns3:Id>0</ns3:Id>
</ns3:SendCtg>
<ns3:Sndr>KAREPANOV</ns3:Sndr>
<ns3:Rcpn>PRONOVOST</ns3:Rcpn>
</ns3:UserParameters>
</ns3:historyRecord>
<ns3:historyRecord>
<ns3:AddressParameters>
<ns3:OperationAddress>
<ns3:Index>102972</ns3:Index>
<ns3:Description>MR LC Vnukovo MMPO Cex-2</ns3:Description>
</ns3:OperationAddress>
<ns3:MailDirect>
<ns3:Id>840</ns3:Id>
<ns3:Code2A>US</ns3:Code2A>
<ns3:Code3A>USA</ns3:Code3A>
<ns3:NameRU>??????????? ????? ???????</ns3:NameRU>
<ns3:NameEN>United States</ns3:NameEN>
</ns3:MailDirect>
<ns3:CountryFrom>
<ns3:Id>643</ns3:Id>
<ns3:Code2A>RU</ns3:Code2A>
<ns3:Code3A>RUS</ns3:Code3A>
<ns3:NameRU>?????????? ?????????</ns3:NameRU>
<ns3:NameEN>Russian Federation</ns3:NameEN>
</ns3:CountryFrom>
<ns3:CountryOper>
<ns3:Id>643</ns3:Id>
<ns3:Code2A>RU</ns3:Code2A>
<ns3:Code3A>RUS</ns3:Code3A>
<ns3:NameRU>?????????? ?????????</ns3:NameRU>
<ns3:NameEN>Russian Federation</ns3:NameEN>
</ns3:CountryOper>
</ns3:AddressParameters>
<ns3:FinanceParameters>
<ns3:Payment>0</ns3:Payment>
<ns3:Value>0</ns3:Value>
<ns3:MassRate>0</ns3:MassRate>
<ns3:InsrRate>0</ns3:InsrRate>
<ns3:AirRate>0</ns3:AirRate>
<ns3:Rate>0</ns3:Rate>
<ns3:CustomDuty>0</ns3:CustomDuty>
</ns3:FinanceParameters>
<ns3:ItemParameters>
<ns3:Barcode>RB842972220RU</ns3:Barcode>
<ns3:Internum>RB842972220RU</ns3:Internum>
<ns3:ValidRuType>false</ns3:ValidRuType>
<ns3:ValidEnType>false</ns3:ValidEnType>
<ns3:ComplexItemName>Small packet registered</ns3:ComplexItemName>
<ns3:MailRank>
<ns3:Id>0</ns3:Id>
<ns3:Name>Without rank</ns3:Name>
</ns3:MailRank>
<ns3:PostMark>
<ns3:Id>0</ns3:Id>
<ns3:Name>Without mark</ns3:Name>
</ns3:PostMark>
<ns3:MailType>
<ns3:Id>5</ns3:Id>
<ns3:Name>Small packet</ns3:Name>
</ns3:MailType>
<ns3:MailCtg>
<ns3:Id>1</ns3:Id>
<ns3:Name>Registered</ns3:Name>
</ns3:MailCtg>
<ns3:Mass>1700</ns3:Mass>
</ns3:ItemParameters>
<ns3:OperationParameters>
<ns3:OperType>
<ns3:Id>10</ns3:Id>
<ns3:Name>Export of international mail</ns3:Name>
</ns3:OperType>
<ns3:OperAttr>
<ns3:Id>0</ns3:Id>
</ns3:OperAttr>
<ns3:OperDate>2017-01-03T20:48:24.000+03:00</ns3:OperDate>
</ns3:OperationParameters>
<ns3:UserParameters>
<ns3:SendCtg>
<ns3:Id>0</ns3:Id>
</ns3:SendCtg>
<ns3:Sndr>KAREPANOV</ns3:Sndr>
<ns3:Rcpn>PRONOVOST</ns3:Rcpn>
</ns3:UserParameters>
</ns3:historyRecord>
</ns3:OperationHistoryData>
</ns7:getOperationHistoryResponse>
</S:Body>
</S:Envelope>

You can use the last()-test on node sets:
para[last()] selects the last para child of the context node
Concerning your question this would look as follows.
(//ns3:Name)[last()] | (//ns3:OperDate)[last()]
when applied to your sample xml, this expression yields the following result:
<ns3:Name>Export of international mail</ns3:Name>
<ns3:OperDate>2017:01:03T20:48:24.000+03:00</ns3:OperDate>

Related

walmart upload an item feed sample xml

I need any sample working XML for upload an item using walmart api.
I have tried a lot to create an XML but no success.
Below is my testing XML Data.
<?xml version="1.0" encoding="UTF-8" ?>
<MPItemFeed xmlns="http://walmart.com/">
<MPItemFeedHeader>
<version>3.1</version>
</MPItemFeedHeader>
<MPItem>
<sku>78350426190609</sku>
<processMode>CREATE</processMode>
<productIdentifiers>
<productIdentifier>
<productIdType>UPC</productIdType>
<productId>78350426113604</productId>
</productIdentifier>
</productIdentifiers>
<MPProduct>
<productName>Electronic Cables_ Update3</productName>
<ProductIdUpdate>Yes</ProductIdUpdate>
<SkuUpdate>No</SkuUpdate>
<category>
<Electronics>
<ElectronicsCables>
<shortDescription>new United Facility Supply High-Volume Wrapping paper this is change to Partial update on PROMode is REPLACE_ALL</shortDescription>
<manufacturer>ECManu</manufacturer>
<manufacturerPartNumber>ECManu0354</manufacturerPartNumber>
<modelNumber>ECMan49_update</modelNumber>
<brand>NewECB brand</brand>
<mainImageUrl>https://i5.walmartimages.com/asr/d225a57c-18fa-46f1-b160-7e61a6fae8b1_1.487e4418d1c56266742b8a6942a3ac5e.jpeg</mainImageUrl>
<productSecondaryImageURL>
<productSecondaryImageURLValue>https://i5.walmartimages.com/asr/414422b1-b13a-40b5-9bdc-adfe24a0bad8_1.3473a55982153dc1dfb17294123124f5.jpeg</productSecondaryImageURLValue>
</productSecondaryImageURL>
<color>Blue</color>
<cableLength>
<measure>18.00</measure>
<unit>in</unit>
</cableLength>
<batteryTechnologyType>Alkaline</batteryTechnologyType>
<isProp65WarningRequired>No</isProp65WarningRequired>
</ElectronicsCables>
</Electronics>
</category>
</MPProduct>
</MPItem>
</MPItemFeed>
I am getting this response.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:PartnerFeedResponse xmlns:ns2="http://walmart.com/">
<ns2:feedId>A9CCFBD2054B43859744FE50DFADB9B3#AQMBAAA</ns2:feedId>
<ns2:feedStatus>PROCESSED</ns2:feedStatus>
<ns2:ingestionErrors/>
<ns2:itemsReceived>1</ns2:itemsReceived>
<ns2:itemsSucceeded>0</ns2:itemsSucceeded>
<ns2:itemsFailed>1</ns2:itemsFailed>
<ns2:itemsProcessing>0</ns2:itemsProcessing>
<ns2:offset>0</ns2:offset>
<ns2:limit>50</ns2:limit>
<ns2:itemDetails/>
</ns2:PartnerFeedResponse>
How can I fix the above XML data?
Swap the positions of the processMode and sku tags like so:
<MPItem>
<processMode>CREATE</processMode>
<sku>78350426190609</sku>
<productIdentifiers>
You can find the current XSDs at
https://developer.walmart.com/xsd/V3-Spec-Item-3.1-XSD.zip
-
You may want to look into an XML validator to help find errors like this.
The below XML is a sample XML for v3 item feed for Walmart Product Upload
<?xml version="1.0"?>
<MPItemFeed xmlns="http://walmart.com/">
<MPItemFeedHeader>
<version>3.1</version>
<mart>WALMART_CA</mart>
<locale>en_CA</locale>
</MPItemFeedHeader>
<MPItem>
<sku>437764</sku>
<productIdentifiers>
<productIdentifier>
<productIdType>UPC</productIdType>
<productId>028617433790</productId>
</productIdentifier>
</productIdentifiers>
<MPProduct>
<productName>Bistro Chalk Marker Chisel Tip-Silver 483-C-SLV</productName>
<ProductIdUpdate>No</ProductIdUpdate>
<SkuUpdate>No</SkuUpdate>
<category>
<ArtAndCraftCategory>
<ArtAndCraft>
<shortDescription>Bistro Chalk Marker Chisel Tip-Silver 483-C-SLV</shortDescription>
<brand>Uchida</brand>
<mainImageUrl>https://www.stuff4crafts.com/media/catalog/product/4/3/437764.jpg</mainImageUrl>
</ArtAndCraft>
</ArtAndCraftCategory>
</category>
</MPProduct>
<MPOffer>
<price>3.99</price>
<MinimumAdvertisedPrice>3.99</MinimumAdvertisedPrice>
<ShippingWeight>
<measure>0.8000</measure>
<unit>lb</unit>
</ShippingWeight>
<ProductTaxCode>2038710</ProductTaxCode>
</MPOffer>
</MPItem>
</MPItemFeed>
processMode is default CREATE . You can either use it or skip it. If used it should be above tag.

Getting info from a specific XML Node

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

PHP: XML C14n for SEPA container file hash

Similarly to this question, I'm trying to calculate a document hash value for a SEPA container file. This is the container my code currently generates:
<?xml version="1.0" encoding="UTF-8"?>
<conxml xmlns="urn:conxml:xsd:container.nnn.003.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:conxml:xsd:container.nnn.003.02 container.nnn.003.02.xsd">
<ContainerId>
<SenderId>TEST</SenderId>
<IdType>EBIC</IdType>
<TimeStamp>090237000</TimeStamp>
</ContainerId>
<CreDtTm>2014-02-14T09:32:37+01:00</CreDtTm>
<MsgPain008>
<HashValue>942AB2F57DBAF6302EDC526472098DF38C540EB75E1913DAB0DF416D168C3253</HashValue>
<HashAlgorithm>SHA256</HashAlgorithm>
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.003.02">
<CstmrDrctDbtInitn>
<GrpHdr>
<MsgId>testmsg-1</MsgId>
<CreDtTm>2014-02-14T09:32:37+01:00</CreDtTm>
<NbOfTxs>1</NbOfTxs>
<CtrlSum>0.01</CtrlSum>
<InitgPty>
<Nm>TestCo</Nm>
</InitgPty>
</GrpHdr>
<PmtInf>
<PmtInfId>testmsg-1-pmt-1</PmtInfId>
<PmtMtd>DD</PmtMtd>
<BtchBookg>true</BtchBookg>
<NbOfTxs>1</NbOfTxs>
<CtrlSum>0.01</CtrlSum>
<PmtTpInf>
<SvcLvl>
<Cd>SEPA</Cd>
</SvcLvl>
<LclInstrm>
<Cd>CORE</Cd>
</LclInstrm>
<SeqTp>OOFF</SeqTp>
</PmtTpInf>
<ReqdColltnDt>2014-02-14+01:00</ReqdColltnDt>
<Cdtr>
<Nm>TestCo</Nm>
</Cdtr>
<CdtrAcct>
<Id>
<IBAN>DE54100000000000012345</IBAN>
</Id>
</CdtrAcct>
<CdtrAgt>
<FinInstnId>
<BIC>MARKDEF1100</BIC>
</FinInstnId>
</CdtrAgt>
<CdtrSchmeId>
<Id>
<PrvtId>
<Othr>
<Id>DE46ZZZ00000012345</Id>
<SchmeNm>
<Prtry>SEPA</Prtry>
</SchmeNm>
</Othr>
</PrvtId>
</Id>
</CdtrSchmeId>
<DrctDbtTxInf>
<PmtId>
<EndToEndId>testmsg-1-2</EndToEndId>
</PmtId>
<InstdAmt Ccy="EUR">0.01</InstdAmt>
<DrctDbtTx>
<MndtRltdInf>
<MndtId>Test-1</MndtId>
<DtOfSgntr>2014-02-14+01:00</DtOfSgntr>
</MndtRltdInf>
</DrctDbtTx>
<DbtrAgt>
<FinInstnId>
<BIC>MARKDEF1200</BIC>
</FinInstnId>
</DbtrAgt>
<Dbtr>
<Nm>Other Test</Nm>
</Dbtr>
<DbtrAcct>
<Id>
<IBAN>DE90200000000000098765</IBAN>
</Id>
</DbtrAcct>
<RmtInf>
<Ustrd>Test</Ustrd>
</RmtInf>
</DrctDbtTxInf>
</PmtInf>
</CstmrDrctDbtInitn>
</Document>
</MsgPain008>
</conxml>
According to a bank-supplied format checking tool my file is mostly correct, except for the hash. Since PHP's implementation of SHA256 is probably not at fault I think I'm doing something wrong when canonicalizing the document.
The code in question is rather simple:
function documentHash($element)
{
$text = $element->C14N(true, true);
return strtoupper(hash('sha256', $text));
}
$element is the DOMElement containing the <Document> node. This function is called during the creation of the container file; thus the xmlns:xsi parameter is not applied to the node. However, manually adding it did not seem to improve matters.
The generated hash is wrong - it's 058098433DAC5D66ED34933CFFD98BF65CAD5C97CC45F9B0619B1FF96C3930E7; the expected value according to the format checker is 942AB2F57DBAF6302EDC526472098DF38C540EB75E1913DAB0DF416D168C3253. Now the question is what I'm doing wrong here - or rather how the I have to massage my XML in order to please the bank.
Here is what $text looks like: (Unfortunately, canonicalized XML does not make for pretty code blocks.)
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.003.02"><CstmrDrctDbtInitn><GrpHdr><MsgId>testmsg-1</MsgId><CreDtTm>2014-02-14T09:32:37+01:00</CreDtTm><NbOfTxs>1</NbOfTxs><CtrlSum>0.01</CtrlSum><InitgPty><Nm>TestCo</Nm></InitgPty></GrpHdr><PmtInf><PmtInfId>testmsg-1-pmt-1</PmtInfId><PmtMtd>DD</PmtMtd><BtchBookg>true</BtchBookg><NbOfTxs>1</NbOfTxs><CtrlSum>0.01</CtrlSum><PmtTpInf><SvcLvl><Cd>SEPA</Cd></SvcLvl><LclInstrm><Cd>CORE</Cd></LclInstrm><SeqTp>OOFF</SeqTp></PmtTpInf><ReqdColltnDt>2014-02-14+01:00</ReqdColltnDt><Cdtr><Nm>TestCo</Nm></Cdtr><CdtrAcct><Id><IBAN>DE54100000000000012345</IBAN></Id></CdtrAcct><CdtrAgt><FinInstnId><BIC>MARKDEF1100</BIC></FinInstnId></CdtrAgt><CdtrSchmeId><Id><PrvtId><Othr><Id>DE46ZZZ00000012345</Id><SchmeNm><Prtry>SEPA</Prtry></SchmeNm></Othr></PrvtId></Id></CdtrSchmeId><DrctDbtTxInf><PmtId><EndToEndId>testmsg-1-2</EndToEndId></PmtId><InstdAmt Ccy="EUR">0.01</InstdAmt><DrctDbtTx><MndtRltdInf><MndtId>Test-1</MndtId><DtOfSgntr>2014-02-14+01:00</DtOfSgntr></MndtRltdInf></DrctDbtTx><DbtrAgt><FinInstnId><BIC>MARKDEF1200</BIC></FinInstnId></DbtrAgt><Dbtr><Nm>Other Test</Nm></Dbtr><DbtrAcct><Id><IBAN>DE90200000000000098765</IBAN></Id></DbtrAcct><RmtInf><Ustrd>Test</Ustrd></RmtInf></DrctDbtTxInf></PmtInf></CstmrDrctDbtInitn></Document>

PHP newbie- specific scenario on how to parse an XML value stored in a variable using SimpleXML [duplicate]

This question already has an answer here:
php simple xml parse problem on invalid tags
(1 answer)
Closed 9 years ago.
I want to parse an XML data stored in a variable, using Simple XML.
THis is the data I am talking about:
<SearchResults:searchresults xsi:schemaLocation="http://www.zillow.com/static/xsd/SearchResults.xsd /vstatic/ae1bf8a790b67ef2e902d2bc04046f02/static/xsd/SearchResults.xsd">
<request>
<address>2114 Bigelow Ave</address>
<citystatezip>Seattle, WA</citystatezip>
</request>
<message>
<text>Request successfully processed</text>
<code>0</code>
</message>
<response>
<results>
<result>
<zpid>48749425</zpid>
<links>
<homedetails>http://www.zillow.com/homedetails/2114-Bigelow-Ave-N-Seattle-WA-98109/48749425_zpid/</homedetails>
<graphsanddata>http://www.zillow.com/homedetails/charts/48749425_zpid,1year_chartDuration/?cbt=7522682882544325802%7E9%7EY2EzX18jtvYTCel5PgJtPY1pmDDLxGDZXzsfRy49lJvCnZ4bh7Fi9w**</graphsanddata>
<mapthishome>http://www.zillow.com/homes/map/48749425_zpid/</mapthishome>
<comparables>http://www.zillow.com/homes/comps/48749425_zpid/</comparables>
</links>
<address>
<street>2114 Bigelow Ave N</street>
<zipcode>98109</zipcode>
<city>Seattle</city>
<state>WA</state>
<latitude>47.63793</latitude>
<longitude>-122.347936</longitude>
</address>
<zestimate>
<amount currency="USD">1219500</amount>
<last-updated>11/03/2009</last-updated>
<oneWeekChange deprecated="true"/>
<valueChange duration="30" currency="USD">-41500</valueChange>
<valuationRange>
<low currency="USD">1024380</low>
<high currency="USD">1378035</high>
</valuationRange>
<percentile>0</percentile>
</zestimate>
<localRealEstate>
<region id="271856" type="neighborhood" name="East Queen Anne">
<zindexValue>525,397</zindexValue>
<zindexOneYearChange>-0.144</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/East-Queen-Anne/r_271856/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/East-Queen-Anne-Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/east-queen-anne-seattle-wa/</forSale>
</links>
</region>
<region id="16037" type="city" name="Seattle">
<zindexValue>381,764</zindexValue>
<zindexOneYearChange>-0.074</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-Seattle/r_16037/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/Seattle-WA/</forSaleByOwner>
<forSale>http://www.zillow.com/seattle-wa/</forSale>
</links>
</region>
<region id="59" type="state" name="Washington">
<zindexValue>263,278</zindexValue>
<zindexOneYearChange>-0.066</zindexOneYearChange>
<links>
<overview>http://www.zillow.com/local-info/WA-home-value/r_59/</overview>
<forSaleByOwner>http://www.zillow.com/homes/fsbo/WA/</forSaleByOwner>
<forSale>http://www.zillow.com/wa/</forSale>
</links>
</region>
</localRealEstate>
</result>
</results>
</response>
</SearchResults:searchresults>
Now the above type of XML is stored in variable named $zillow_data
First I load it using SimpleXML using the code
$xml = simplexml_load_string($zillow_data);
Now, I want to get the "message" value as shown in the XML data above.
When I try
foreach($xml->message[0]->text[0] as $response)
It does not work.
When I try something like the below code I get an error in Netbeans IDE
foreach($xml->SearchResults:searchresults[0]->message[0]->text[0] as $response)
The error I get is "unexpected : "
How do I correctly fetch the message in above XML data?
Also how do I parse through all the "result" elements, one by one?
If You use the code:
$xml = simplexml_load_string($string);
while the $string variable contains the XML, the first element <SearchResults:searchresults> becomes the main $xml SimpleXMLElement object, while the child tags <request>, <message> and <response> are its properties.
Thus, forgetting about the undefined namespace warnings, You should be able to do e.g.:
foreach($xml->response->results->result as $result) {
echo (string) $result->zpid;
}
There is only one message with only one text element, thus if You want to echo this one, You should only do:
echo (string) $xml->message->text;
Do a var_dump($xml); to understand the XML structure being transformed into objects and arrays after loading it with SimpleXML.

hostip.info - Parse API response with SimpeXML

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']

Categories