I cannot figure out how does this thing work. I followed Instruction from PHP Doc.
Here is my code:
$xmlfile = simplexml_load_file($xmlurl) or die("Cannon get.");
The file contains following schema:
<PriceResult>
<QueryStatus>
</QueryStatus>
<InputData>
</InputData>
<Producers/>
<Prices>
<Price>
</Price>
<Price>
<PartId>13580448730</PartId>
<BrandId>11</BrandId>
<Brand>BERU</Brand>
<PartNumber>Z226</PartNumber>
<PartNumberShort>Z226</PartNumberShort>
<PartDescriptionRus/>
<Price>8.90</Price>
<Currency>EUR</Currency>
<Quantity>0</Quantity>
<QuantityType>EQUAL</QuantityType>
<PriceLogo>GLIR</PriceLogo><Weight/>
<PriceDescrShort>Европейский поставщик запчастей</PriceDescrShort>
<PriceDescrLong>Европейский поставщик запчастей</PriceDescrLong>
<DeliveryType>LOCAL</DeliveryType>
<DeliveryDays>17</DeliveryDays>
<PriceChangeDate>2015-01-05 10:27:05</PriceChangeDate>
<DamagedFlag>N</DamagedFlag>
<UsedFlag>N</UsedFlag>
<OriginalFlag>N</OriginalFlag>
<OldPartNumberFlag>N</OldPartNumberFlag>
<Group>0</Group><GroupDescr/>
</Price>
<Price>
</Price>
<Price>
</Price>
</PriceResult>
I did that before, but now I forgot. So how could I iterate XML through Price in Prices to be able get data like this:
foreach ($xmlfile->children() as $item){
print($item->BrandId);
}
and Ill get all the brands, or $item->PartId - all the part? e.t.c to all
$xmlfile = simplexml_load_file($xmlurl) or die("Cannon get.");
Then
$xxx= $xmlfile->xxx;
$yyy = $xmlfile->yyy;
$zzz = $xmlfile->zzz;
After all, it's more simple to show data like this
echo $xxx;
And where is your "->children() " ?
Related
I'm trying to combine multiple XML files, using SimpleXML if possible. I'm just trying to append products, children, and child data from file 2 into file 1. I'm not trying to merge elements, just append file 2 to the bottom of file 1, and so on. (Though I guess this is technically merging merchandiser elements?) The files contain the same schema and will both look similar to the example below, only thing that will be changing is the actual text. This is just XML for two different products, I added a large space in between products so that it's easier to see where it ends.
<merchandiser xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="merchandiser.xsd">
<header>
<merchantId>35928</merchantId>
<merchantName>Sunspel Clothing</merchantName>
<createdOn>01/14/2016 02:03:31</createdOn>
</header>
<product product_id="14633" name="Cotton Socks" sku_number="1588/102">
<category>
<primary>Accessories</primary>
<secondary>Men's~~Socks</secondary>
</category>
<URL>
<product>
http://click.linksynergy.com/link?id=D*rqD2paIXY&offerid=191965.14633&type=15&murl=http%3A%2F%2Fwww.sunspel.com%2Fuk%2Fcotton-sock-black.html
</product>
<productImage>
http://www.sunspel.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/1/5/1588-102-new.jpg
</productImage>
</URL>
<description>
<short>
Our new cotton socks are designed by Sunspel and crafted in an Italian factory steeped in years of experience, skill and heritage. They are made from the highest quality, extra-long staple Egyptian cotton yarn which, prior to knitting is combed, twisted and mercerised to enhance the comfort, shine and absorption of the fabric as well as its resistance to pilling and shrinking.
</short>
</description>
<discount currency="GBP">
<type>amount</type>
</discount>
<price currency="GBP">
<retail>15.00</retail>
</price>
<shipping>
<availability>in-stock</availability>
</shipping>
<pixel>
http://ad.linksynergy.com/fs-bin/show?id=D*rqD2paIXY&bids=191965.14633&type=15&subid=0
</pixel>
</product>
<product product_id="15115" name="Cotton Socks" sku_number="1589/236">
<category>
<primary>Accessories</primary>
<secondary>Men's~~Socks~~Men's</secondary>
</category>
<URL>
<product>
http://click.linksynergy.com/link?id=D*rqD2paIXY&offerid=191965.15115&type=15&murl=http%3A%2F%2Fwww.sunspel.com%2Fuk%2Fmens-cotton-socks-navy-stripes.html
</product>
<productImage>
http://www.sunspel.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/1/5/1588-236-new.jpg
</productImage>
</URL>
<description>
<short>
Our new cotton socks are designed by Sunspel and crafted in an Italian factory steeped in years of experience, skill and heritage. They are made from the highest quality, extra-long staple Egyptian cotton yarn which, prior to knitting is combed, twisted and mercerised to enhance the comfort, shine and absorption of the fabric as well as its resistance to pilling and shrinking.
</short>
</description>
<discount currency="GBP">
<type>amount</type>
</discount>
<price currency="GBP">
<retail>17.00</retail>
</price>
<shipping>
<availability>in-stock</availability>
</shipping>
<pixel>
http://ad.linksynergy.com/fs-bin/show?id=D*rqD2paIXY&bids=191965.15115&type=15&subid=0
</pixel>
</product>
<product product_id="15116" name="Cotton Socks" sku_number="1589/711">
<category>
<primary>Accessories</primary>
<secondary>Men's~~Socks~~Men's</secondary>
</category>
<URL>
<product>
http://click.linksynergy.com/link?id=D*rqD2paIXY&offerid=191965.15116&type=15&murl=http%3A%2F%2Fwww.sunspel.com%2Fuk%2Fmens-cotton-socks-charcoal-melange-stripes.html
</product>
<productImage>
http://www.sunspel.com/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/1/5/1588-711-new.jpg
</productImage>
</URL>
<description>
<short>
Our new cotton socks are designed by Sunspel and crafted in an Italian factory steeped in years of experience, skill and heritage. They are made from the highest quality, extra-long staple Egyptian cotton yarn which, prior to knitting is combed, twisted and mercerised to enhance the comfort, shine and absorption of the fabric as well as its resistance to pilling and shrinking.
</short>
</description>
<discount currency="GBP">
<type>amount</type>
</discount>
<price currency="GBP">
<retail>17.00</retail>
</price>
<shipping>
<availability>in-stock</availability>
</shipping>
<pixel>
http://ad.linksynergy.com/fs-bin/show?id=D*rqD2paIXY&bids=191965.15116&type=15&subid=0
</pixel>
</product>
With some foreach statements I'm able to append all product children and attributes, but this doesn't actually give me the child data.
$file1 = '35928_3210820_mp.xml';
$file2 = '39153_3210820_mp.xml';
$fileout = 'ukmerge.xml';
$xml1 = simplexml_load_file( $file1 );
$xml2 = simplexml_load_file( $file2 ); // loop through the product and add them and their attributes to xml1
$product = $xml2->product;
$prod = $xml2->merchandiser->header->product;
$category = $product->category;
$url = $product->URL;
$description = $product->description;
foreach( $xml2->children() as $child ) {
$new = $xml1->addChild( $child->getName() , htmlspecialchars($child) );
foreach( $child->attributes() as $key => $value ) {
$new->addAttribute( $key, $value );
}
} $fh = fopen( $fileout, 'w') or die ( "can't open file $fileout" );
fwrite( $fh, $xml1->asXML() );
fclose( $fh );
When I try to add on from there then everything gets messed up and nothing is in the correct place/order anymore. I'd also like to put this into a function since I'm going to be doing it often. Any help is greatly appreciate as I've been struggling with this for a few days now and have scowered over a few dozen stackoverflow and php.net threads.
One of the things that's confusing me is the <merchandiser> and <header> tags that every file starts with. Once the merchandiser tag ends it is the end of the document so I need to take only what's inside the merchandiser tag of file 2 and append it inside the merchandiser tag of file 1. The header tag just confuses me cause I'm not sure if it's gets in the way or not.
As preliminary note, your XML sample is malformed. Also it is not coherent with your code (i.e. there is not ->merchandiser->header->product ).
So, in this example I will use a different sample, like this one (file1.xml):
<root>
<product>
<name>Product 1</name>
</product>
<product>
<name>Product 2</name>
</product>
</root>
and this one (file2.xml):
<root>
<product>
<name>Product 3</name>
</product>
<product>
<name>Product 4</name>
</product>
</root>
You don't want to use DOMDocument->importNode() due “it kept throwing a lot of errors”.
You can use DOMDocument in conjunction with SimpleXML and dom_import_simplexml() function.
First of all, prepare destination XML: load the file with SimpleXML, create a DOMDocument using dom_import_simplexml() and set $parent variable to <root> element:
$dst = simplexml_load_file( 'file1.xml' );
$dst = dom_import_simplexml( $dst )->ownerDocument;
$parent = $dst->getElementsByTagName( 'root' )->item(0);
Then, load second file with SimpleXML:
$src = simplexml_load_file( 'file2.xml' );
Through a foreach() loop, import each <product> element from SimpleXML to DOMDocument and appent it as child of $parent node:
foreach( $src->product as $product )
{
$node = dom_import_simplexml( $product );
$node = $dst->importNode( $node, 1 );
$parent->appendChild( $node );
}
Now, your merged XML is ready. You can print it using $dst->saveXML().
I've not be able to product a correctly indented XML. BTW to do this, you can reload-it:
$final = new DOMDocument();
$final->loadXML( $dst->saveXML(), LIBXML_NOBLANKS );
$final->formatOutput = True;
echo $final->saveXML();
Final output:
<?xml version="1.0"?>
<root>
<product>
<name>Product 1</name>
</product>
<product>
<name>Product 2</name>
</product>
<product>
<name>Product 3</name>
</product>
<product>
<name>Product 4</name>
</product>
</root>
here is my amazon mws api responce
<?xml version="1.0"?>
<GetMyPriceForSKUResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMyPriceForSKUResult SellerSKU="ds-tru-6sss" status="Success">
<Product xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>Assssssss</MarketplaceId>
<ASIN>sss</ASIN>
</MarketplaceASIN>
<SKUIdentifier>
<MarketplaceId>Afasrfd</MarketplaceId>
<SellerId>ssssss</SellerId>
<SellerSKU>dssss</SellerSKU>
</SKUIdentifier>
</Identifiers>
<Offers>
<Offer>
<BuyingPrice>
<LandedPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>12.49</Amount>
</LandedPrice>
<ListingPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>12.49</Amount>
</ListingPrice>
<Shipping>
<CurrencyCode>USD</CurrencyCode>
<Amount>0.00</Amount>
</Shipping>
</BuyingPrice>
<RegularPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>12.49</Amount>
</RegularPrice>
<FulfillmentChannel>MERCHANT</FulfillmentChannel>
<ItemCondition>New</ItemCondition>
<ItemSubCondition>New</ItemSubCondition>
<SellerId>Aadada</SellerId>
<SellerSKU>ssss</SellerSKU>
</Offer>
<Offer>
<BuyingPrice>
<LandedPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>1000.00</Amount>
</LandedPrice>
<ListingPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>1000.00</Amount>
</ListingPrice>
<Shipping>
<CurrencyCode>USD</CurrencyCode>
<Amount>0.00</Amount>
</Shipping>
</BuyingPrice>
<RegularPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>1000.00</Amount>
</RegularPrice>
<FulfillmentChannel>MERCHANT</FulfillmentChannel>
<ItemCondition>New</ItemCondition>
<ItemSubCondition>New</ItemSubCondition>
<SellerId>ssss</SellerId>
<SellerSKU>sss</SellerSKU>
</Offer>
</Offers>
</Product>
</GetMyPriceForSKUResult>
<ResponseMetadata>
<RequestId>e0ef1c2c-4f35-4316-8629-faadadd</RequestId>
</ResponseMetadata>
</GetMyPriceForSKUResponse>
and to select amount (12.49) from
<ListingPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>12.49</Amount>
</ListingPrice>
I am trying ,
// from curl
$result = curl_exec ($ch);
$xmldoc = new DOMDocument();
$xmldoc->load($result);
$xpathvar = new Domxpath($xmldoc);
$queryResult = $xpathvar->query('/Amount');
foreach($queryResult as $result){
echo $result;
}
I am expecting more then one value for this, but I am getting none at all.
Sorry, I am not good at XPath, can somebody guide me?
Currently I found errors in your code:
First: Use two // to select an element regardless of where it is located in the xml tree.
$queryResult = $xpathvar->query('//Amount');
Second: thanks #Ranon. You'll take care of the documents xml namespace:
// Register Namespace mws
$xpathvar->registerNamespace("mws", 'http://mws.amazonservices.com/schema/Products/2011-10-01');
... and use it, means:
$queryResult = $xpathvar->query('//mws:Amount');
Third: If you want to select the text node (between the <amount> nodes) you should use:
$queryResult = $xpathvar->query('//mws:Amount/text()');
Otherwise you can select the parent element <Amount> (as you already doing) and retrieve the value with PHP. Then you have to change your code to:
$queryResult = $xpathvar->query('//mws:Amount');
foreach($queryResult as $result){
echo $result->nodeValue; // echo the node value, not the node 'itself'
}
Fourth: Also note another error in your code. When you create a DOMDocument from an xml string you'll have to use:
$document->loadXML($result);
Fifth: You told that you want to retrieve the <Amount> elements form inside <ListingPrice> elements. Note that there are also <Amount> elements inside <RegularPrice> elements. So it does matter where the <Amount> element is located in tree. Use the following query to obtain only listing price amounts:
$queryResult = $xpathvar->query('//mws:ListingPrice/mws:Amount');
Amazon returns XML using a namespace which you have to declare and use.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// from curl
$result = curl_exec($ch);
$xmldoc = new DOMDocument();
$xmldoc->loadXML($result);
$xpathvar = new Domxpath($xmldoc);
// Register Namespace mws
$xpathvar->registerNamespace("mws", 'http://mws.amazonservices.com/schema/Products/2011-10-01');
// Query using namespace mws
$queryResult = $xpathvar->query('//mws:Amount');
foreach($queryResult as $result){
echo $result->nodeValue;
}
I selected the namespace identifier mws arbitrarily from the subdomain, you can choose another if you want.
I corrected some other errors in the code found by #hek2mgl.
The XPath expression is wrong. You need '//Amount' to select all the "Amount" elements
I know this has been asked before, and I have tried a few of the suggestions, but I am not getting the information from the XML file. I need to get the number of sellers (OfferListingCount condition="Any")from an xml file. Here is the XML:
<?xml version="1.0"?>
<GetCompetitivePricingForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetCompetitivePricingForASINResult ASIN="0312479743" status="Success">
<Product xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
<ASIN>0312479743</ASIN>
</MarketplaceASIN>
</Identifiers>
<CompetitivePricing>
<CompetitivePrices>
<CompetitivePrice belongsToRequester="false" condition="Used" subcondition="Good">
<CompetitivePriceId>2</CompetitivePriceId>
<Price>
<LandedPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>36.23</Amount>
</LandedPrice>
<ListingPrice>
<CurrencyCode>USD</CurrencyCode>
<Amount>36.23</Amount>
</ListingPrice>
<Shipping>
<CurrencyCode>USD</CurrencyCode>
<Amount>0.00</Amount>
</Shipping>
</Price>
</CompetitivePrice>
</CompetitivePrices>
<NumberOfOfferListings>
<OfferListingCount condition="Any">34</OfferListingCount>
<OfferListingCount condition="Used">29</OfferListingCount>
<OfferListingCount condition="New">5</OfferListingCount>
</NumberOfOfferListings>
Here is my UPDATED code for Php:
$priceComp_xml = amazonCompPrice_xml($asin);
$compPricing = $priceComp_xml->xpath('/OfferListingCount[#condition="Any"]');
$priceComp_xml returns the information from the xml file, and I am trying to use the next line to get the information I need. When I run the code, get an empty array.
How do I get this information?
http://php.net/manual/en/function.simplexml-load-file.php
$xml = simplexml_load_file($xml_file);
$output = array();
foreach ($xml as $row => $item_data)
{
// Attributes
$attributes = $item_data->attributes();
Load it up, get the attributes.
I work with many different types of xml files. I load the contents of these into my mysql database. Problem is that i need to define the tags I want to pick everytime.
Is there a php dom object functions that can iterate over all the tags and give them to me.
this is my sample xml
<products>
<product>
<name>Name of product</name>
<categories>
<category>Apparel</category>
<category>Trousers</category>
<category>Blue</category>
</categories>
<description>Blue trousers</description>
<price>599.00</price> <regularPrice>599.00</regularPrice>
</product>
</products>
Output should be NOT the values but the acctual name of the XML tags, in this case it should be
Products, Product, Name, Categories, category, description, price
Getting those values I could dynamicly point them via a connection table to always be save in the right table and in the right field.
*Try this code it will work as expected *
$xmlD = '
<products>
<product>
<name>Name of product</name>
<categories>
<category>Apparel</category>
<category>Trousers</category>
<category>Blue</category>
</categories>
<description>Blue trousers</description>
<price>599.00</price> <regularPrice>599.00</regularPrice>
</product>
</products>
';
$xml = simplexml_load_string($xmlD);
echo $xml->getName() . "<br />";
foreach($xml->children() as $child)
{
echo $child->getName(). "<br />";
foreach($child->children() as $innerChild):
echo $innerChild->getName(). "<br />";
endforeach;
}
I've been tearing my hair out with this now for a few hours and thought I'd post it up here to see if anybody had any suggestions.
Basically I am receving some XML date via SOAP/Curl call which looks like this:
<?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>
<LocationAvailabilityResponse xmlns="">
<getAvailabilityReturn>
<errors />
<requestID>389851</requestID>
<hotels>
<hotels>
<hotel>
<apt>false</apt>
<distance>0</distance>
<fromPrice>18.5</fromPrice>
<hotelName>Britannia Hotel Stockport</hotelName>
<id>5165</id>
<images>
<images>
<hasThumbnail>true</hasThumbnail>
<height>187</height>
<thumbnailHeight>50</thumbnailHeight>
<thumbnailURL>http://static.superbreak.net/content/images/Hotel/thumbs/britannia_hotel_stockport_swimming_pool_1_swi_5165.JPG</thumbnailURL>
<thumbnailWidth>68</thumbnailWidth>
<title>Britannia Hotel Stockport</title>
<url>http://static.superbreak.net/content/images/Hotel/britannia_hotel_stockport_swimming_pool_1_swi_5165.JPG</url>
<width>257</width>
</images>
<images>
<hasThumbnail>false</hasThumbnail>
<height>187</height>
<thumbnailHeight>0</thumbnailHeight>
<thumbnailURL>http://static.superbreak.net/content/images/Hotel/thumbs/britannia_hotel_stockport_swimming_pool_2_swi_5165.JPG</thumbnailURL>
<thumbnailWidth>0</thumbnailWidth>
<title>Swimming Pool</title>
<url>http://static.superbreak.net/content/images/Hotel/britannia_hotel_stockport_swimming_pool_2_swi_5165.JPG</url>
<width>257</width>
</images>
<images>
<hasThumbnail>false</hasThumbnail>
<height>187</height>
<thumbnailHeight>0</thumbnailHeight>
<thumbnailURL>http://static.superbreak.net/content/images/Hotel/thumbs/britannia_hotel_stockport_hotel_entrance_1_ent_5165.JPG</thumbnailURL>
<thumbnailWidth>0</thumbnailWidth>
<title>Hotel Entrance</title>
<url>http://static.superbreak.net/content/images/Hotel/britannia_hotel_stockport_hotel_entrance_1_ent_5165.JPG</url>
<width>257</width>
</images>
<images>
<hasThumbnail>false</hasThumbnail>
<height>187</height>
<thumbnailHeight>0</thumbnailHeight>
<thumbnailURL>http://static.superbreak.net/content/images/Hotel/thumbs/britannia_hotel_stockport_hotel_gym_1_gym_5165.JPG</thumbnailURL>
<thumbnailWidth>0</thumbnailWidth>
<title>Hotel Gym</title>
<url>http://static.superbreak.net/content/images/Hotel/britannia_hotel_stockport_hotel_gym_1_gym_5165.JPG</url>
<width>257</width>
</images>
<images>
<hasThumbnail>false</hasThumbnail>
<height>187</height>
<thumbnailHeight>0</thumbnailHeight>
<thumbnailURL>http://static.superbreak.net/content/images/Hotel/thumbs/britannia_hotel_stockport_hotel_lounge_1_lou_5165.JPG</thumbnailURL>
<thumbnailWidth>0</thumbnailWidth>
<title>Hotel Lounge</title>
<url>http://static.superbreak.net/content/images/Hotel/britannia_hotel_stockport_hotel_lounge_1_lou_5165.JPG</url>
<width>257</width>
</images>
<images>
<hasThumbnail>false</hasThumbnail>
<height>187</height>
<thumbnailHeight>0</thumbnailHeight>
<thumbnailURL>http://static.superbreak.net/content/images/Hotel/thumbs/britannia_hotel_stockport_four_poster_bedroom_1_pst_5165.JPG</thumbnailURL>
<thumbnailWidth>0</thumbnailWidth>
<title>Four Poster Bedroom</title>
<url>http://static.superbreak.net/content/images/Hotel/britannia_hotel_stockport_four_poster_bedroom_1_pst_5165.JPG</url>
<width>257</width>
</images>
</images>
<latitude>53.398941</latitude>
<location>Stockport</location>
<longitude>-2.13463</longitude>
<starRating>3</starRating>
</hotel>
<roomUnits>
<roomUnits>
<allocation>1</allocation>
<boardCode>RO</boardCode>
<boardDescription>Room only</boardDescription>
<maxOccupancy>2</maxOccupancy>
<minOccupancy>1</minOccupancy>
<price>18.5</price>
<stdOccupancy>2</stdOccupancy>
<unitDescription>Double For 1-2</unitDescription>
<unitID>162</unitID>
</roomUnits>
<roomUnits>
<allocation>1</allocation>
<boardCode>RO</boardCode>
<boardDescription>Room only</boardDescription>
<maxOccupancy>2</maxOccupancy>
<minOccupancy>1</minOccupancy>
<price>18.5</price>
<stdOccupancy>2</stdOccupancy>
<unitDescription>Twin For 1-2</unitDescription>
<unitID>161</unitID>
</roomUnits>
<roomUnits>
<allocation>1</allocation>
<boardCode>RO</boardCode>
<boardDescription>Room only</boardDescription>
<maxOccupancy>2</maxOccupancy>
<minOccupancy>2</minOccupancy>
<price>23.5</price>
<stdOccupancy>2</stdOccupancy>
<unitDescription>Executive Double Room</unitDescription>
<unitID>65</unitID>
</roomUnits>
<roomUnits>
<allocation>1</allocation>
<boardCode>RO</boardCode>
<boardDescription>Room only</boardDescription>
<maxOccupancy>2</maxOccupancy>
<minOccupancy>2</minOccupancy>
<price>23.5</price>
<stdOccupancy>2</stdOccupancy>
<unitDescription>Executive Twin Room</unitDescription>
<unitID>64</unitID>
</roomUnits>
</roomUnits>
</hotels>
I'm attempting to iterate through each hotels hotels result and turn each result into a multi dimensional array. The code I'm using which isn't working as I'd like is below:
$doc = new DOMDocument();
if ($doc->loadXML($result)) {
$items = $doc->getElementsByTagName('hotels');
$hotelnames = array();
foreach($items as $item) {
$hotelname = array();
$hotelimages = array();
if($item->childNodes->length) {
foreach($item->childNodes as $i) {
$hotelname[$i->nodeName] = $i->nodeValue;
if($i->childNodes->length){
foreach($i->childNodes as $z) {
if($z->childNodes->length){
foreach($z->childNodes as $x) {
$hotelimage[$x->nodeName] = $x->nodeValue;
}
}
}
}
$hotelimages[] = $hotelimage;
}
}
$hotelnames[] = $hotelname;
}
}
I'm guessing the issues I'm facing are mostly caused by the fact that the child and parent nodes are named the same for hotels and for the images.
Any help or a nod in the right direction will be much appreciated.
I suggest you using xpath (for example in SimpleXML implementation http://php.net/manual/en/simplexmlelement.xpath.php) for loading the values you need.
Or if you need whole XML parsed to array, you can always use PEAR XML_Serializer package (http://pear.php.net/package/XML_Serializer) to unserialize your XML.
Instead of working directly with the DOM I would recommend that you, unless you actually do need access to the DOM, perform these tasks using SimpleXML
It makes it very easy to work with XML data and you can act on it almost like a normal array.
Example
<?php
$url = 'http://www.flickr.com/services/feeds/photos_public.gne';
foreach(simplexml_load_file($url)->entry as $entry) {
echo $entry->content;
}
?>
Quite few lines for that functionality :)
Good luck!
I am looking in to the XML and I noticed some XML tags are not correct
Ex: <images><images></images><images></images></images> same is the case with roomunit.
I think it should be like <images><image></image><image></image></images> this will help to iterate over XML tag in php.