extract data from an xml file using php - php

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.

Related

Amazon mws Scratch pad - GetMyPriceForSKU returns request id , when will i get prices?

Amazon mws api - Just i am trying to get the prices of a product using mws api scratch pad. I passed one parameter SellerSKUList.SellerSKU.1. It didn't return the prices and produced below response.
<?xml version="1.0"?>
<GetMyPriceForSKUResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMyPriceForSKUResult SellerSKU="AUYyRIG50.011" 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>GIVEN</MarketplaceId>
<ASIN>return_value</ASIN>
</MarketplaceASIN>
<SKUIdentifier>
<MarketplaceId>GIVEN</MarketplaceId>
<SellerId>GIVEN</SellerId>
<SellerSKU>AUYyRIG50.011</SellerSKU>
</SKUIdentifier>
</Identifiers>
<Offers/>
</Product>
</GetMyPriceForSKUResult>
<ResponseMetadata>
<RequestId>0e16e0de-c9e1-4456-864b-e49f2e574575</RequestId>
</ResponseMetadata>
</GetMyPriceForSKUResponse>
Amazon Product's API won't return any pricing data if the product is inactive or out of stock or is merged by different ASIN, else it should return something like below.
<?xml version="1.0"?>
<GetMyPriceForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMyPriceForASINResult ASIN="B009K1T3TY" status="Success">
<Product>
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>A1F83G8C2ARO7P</MarketplaceId>
<ASIN>B009K1T3TY</ASIN>
</MarketplaceASIN>
</Identifiers>
<Offers>
<Offer>
<BuyingPrice>
<LandedPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>3.49</Amount>
</LandedPrice>
<ListingPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>3.49</Amount>
</ListingPrice>
<Shipping>
<CurrencyCode>GBP</CurrencyCode>
<Amount>0.00</Amount>
</Shipping>
</BuyingPrice>
<RegularPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>3.49</Amount>
</RegularPrice>
<FulfillmentChannel>AMAZON</FulfillmentChannel>
<ItemCondition>New</ItemCondition>
<ItemSubCondition>New</ItemSubCondition>
<SellerId>XXXXXXXXXX</SellerId>
<SellerSKU>snl-mldx-pura-7700-20prs-x1a</SellerSKU>
</Offer>
<Offer>
<BuyingPrice>
<LandedPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>3.49</Amount>
</LandedPrice>
<ListingPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>3.49</Amount>
</ListingPrice>
<Shipping>
<CurrencyCode>GBP</CurrencyCode>
<Amount>0.00</Amount>
</Shipping>
</BuyingPrice>
<RegularPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>3.49</Amount>
</RegularPrice>
<FulfillmentChannel>MERCHANT</FulfillmentChannel>
<ItemCondition>New</ItemCondition>
<ItemSubCondition>New</ItemSubCondition>
<SellerId>XXXXXXXXX</SellerId>
<SellerSKU>mldx-pura-7700-20prs-x1a</SellerSKU>
</Offer>
</Offers>
</Product>
</GetMyPriceForASINResult>
<ResponseMetadata>
<RequestId>fb490da2-903b-42ec-afe5-4042e6047519</RequestId>
</ResponseMetadata>
</GetMyPriceForASINResponse>

Only able to select first node when there is a default namespace in xpath

I've been having problems querying an xml file that contains default namespaces and it's been a nightmare.
I've been able to select the first node after declaring a namespace but anything that follows gets ignored.
$str = '<?xml version="1.0"?>
<GetLowestOfferListingsForASINResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetLowestOfferListingsForASINResult>
<Product>
<LowestOfferListings>
<LowestOfferListing>
<Qualifiers>
<ItemCondition>Used</ItemCondition>
<ItemSubcondition>Good</ItemSubcondition>
<FulfillmentChannel>Merchant</FulfillmentChannel>
<ShipsDomestically>Unknown</ShipsDomestically>
<ShippingTime>
<Max>0-2 days</Max>
</ShippingTime>
<SellerPositiveFeedbackRating>95-97%</SellerPositiveFeedbackRating>
</Qualifiers>
<NumberOfOfferListingsConsidered>1</NumberOfOfferListingsConsidered>
<SellerFeedbackCount>83352</SellerFeedbackCount>
<Price>
<LandedPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>7.40</Amount>
</LandedPrice>
<ListingPrice>
<CurrencyCode>GBP</CurrencyCode>
<Amount>4.60</Amount>
</ListingPrice>
<Shipping>
<CurrencyCode>GBP</CurrencyCode>
<Amount>2.80</Amount>
</Shipping>
</Price>
<MultipleOffersAtLowestPrice>False</MultipleOffersAtLowestPrice>
</LowestOfferListing>
</LowestOfferListings>
</Product>
</GetLowestOfferListingsForASINResult>
</GetLowestOfferListingsForASINResponse>';
$xml = new SimpleXMLElement($str);
$xml->registerXPathNamespace('c', 'http://mws.amazonservices.com/schema/Products/2011-10-01');
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult")); //works
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult/Product")); //not working
print_r($xml->xpath("c:GetLowestOfferListingsForASINResult//Product")); //not working
Xpath has no automatic default namespace (it's always the null-namespace), so you need to explicitly use the "c:" prefix with all element names:
c:GetLowestOfferListingsForASINResult/c:Product
^^
c:GetLowestOfferListingsForASINResult//c:Product
^^
if you're interested in the details why this is the case, there is the following existing Q&A on this website:
XPath in SimpleXML for default namespaces without needing prefixes

simplexml parser php iteration

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() " ?

Selecting / Filtering XML Element with XPath

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

get the value of an XML attribute using php

I am attempting to take a value from an attribute and use it in an array to insert it into a MySQL table. My XML file is:
<?xml version="1.0"?>
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMatchingProductForIdResult Id="9780596515898" IdType="ISBN" status="Success">
<Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Product>
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
<ASIN>B0026OR39Y</ASIN>
</MarketplaceASIN>
</Identifiers>
and using php I need to extract out the value of Id in GetMatchingProductForIdResult. So far my code is this:
$parsed_xml = ProductId_xml($isbn);
$isbn13 =(string)$parsed_xml->GetMatchingProductProductForIdResult[0]->attributes();
echo $isbn13['Id']; die;
I am getting no result from the echo statement, even if I change it to print_r or var_dump. I have also tried:
$amazonResult = array(
'isbn' => $parsed_xml->GetMatchingProductProductForIdResult[0]['Id'],
Which yielded no results either. I am not sure where to go from here and any assistance will be greatly appreciated.
EDIT: To clarify this a little bit, the value in Id will change for each record. So what is "9780596515898" this time could be Id="9780596312674" for the next record. I need to know what each one is so I can insert them into the database with the other information I need.
I can access the attributes if I close out the XML - otherwise all it does is throw errors.
You can access all attributes, or individually through simplexml:
$str = <<<XML
<?xml version="1.0"?>
<GetMatchingProductForIdResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
<GetMatchingProductForIdResult Id="9780596515898" IdType="ISBN" status="Success">
<Products xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01" xmlns:ns2="http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd">
<Product>
<Identifiers>
<MarketplaceASIN>
<MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
<ASIN>B0026OR39Y</ASIN>
</MarketplaceASIN>
</Identifiers>
</Product>
</Products>
</GetMatchingProductForIdResult>
</GetMatchingProductForIdResponse>
XML;
$xml = simplexml_load_string($str);
foreach($xml->GetMatchingProductForIdResult->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
// Or access them directly:
echo $xml->GetMatchingProductForIdResult->attributes()->Id;
Outputs:
Id="9780596515898" IdType="ISBN" status="Success" 9780596515898

Categories