解析XML并获取命名空间的值

时间:2015-04-27 12:45:35

标签: php xml parsing

这是我在PHP中生成的XML响应,如何在php中获得ns2:weight?我尝试了几个不同的查询,但无法让它工作。这是亚马逊API的XML响应。

<?xml version="1.0"?>
<GetMatchingProductResponse xmlns="http://mws.amazonservices.com/schema/Products/2011-10-01">
  <GetMatchingProductResult ASIN="B000QSNYGI" 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>B000QSNYGI</ASIN>
        </MarketplaceASIN>
      </Identifiers>
      <AttributeSets>
        <ns2:ItemAttributes xml:lang="en-US">
          <ns2:Binding>Health and Beauty</ns2:Binding>
          <ns2:Brand>Optimum Nutrition</ns2:Brand>
          <ns2:Department>unisex-adult</ns2:Department>
          <ns2:Feature>One 5-pound tub of chocolate-flavored whey protein</ns2:Feature>
          <ns2:Feature>Packed with whey protein isolates</ns2:Feature>
          <ns2:Feature>For maintaining and increasing lean muscle mass</ns2:Feature>
          <ns2:Feature>Instantized to mix easily with a spoon</ns2:Feature>
          <ns2:Feature>Each serving provides over 5 grams of BCAAs</ns2:Feature>
          <ns2:Flavor>Double Rich Chocolate</ns2:Flavor>
          <ns2:ItemDimensions>
            <ns2:Height Units="inches">10.75</ns2:Height>
            <ns2:Length Units="inches">8.00</ns2:Length>
            <ns2:Width Units="inches">8.00</ns2:Width>
            <ns2:Weight Units="pounds">5.00</ns2:Weight>
          </ns2:ItemDimensions>
          <ns2:IsAdultProduct>false</ns2:IsAdultProduct>
          <ns2:IsAutographed>false</ns2:IsAutographed>
          <ns2:IsMemorabilia>false</ns2:IsMemorabilia>
          <ns2:Label>Optimum Nutrition</ns2:Label>
          <ns2:ListPrice>
            <ns2:Amount>82.45</ns2:Amount>
            <ns2:CurrencyCode>USD</ns2:CurrencyCode>
          </ns2:ListPrice>
          <ns2:Manufacturer>Optimum Nutrition</ns2:Manufacturer>
          <ns2:Model>1054618</ns2:Model>
          <ns2:NumberOfItems>1</ns2:NumberOfItems>
          <ns2:PackageDimensions>
            <ns2:Height Units="inches">7.95</ns2:Height>
            <ns2:Length Units="inches">11.50</ns2:Length>
            <ns2:Width Units="inches">7.95</ns2:Width>
            <ns2:Weight Units="pounds">5.65</ns2:Weight>
          </ns2:PackageDimensions>
          <ns2:PackageQuantity>1</ns2:PackageQuantity>
          <ns2:PartNumber>1054618</ns2:PartNumber>
          <ns2:ProductGroup>Health and Beauty</ns2:ProductGroup>
          <ns2:ProductTypeName>HEALTH_PERSONAL_CARE</ns2:ProductTypeName>
          <ns2:Publisher>Optimum Nutrition</ns2:Publisher>
          <ns2:ReleaseDate>2007-05-14</ns2:ReleaseDate>
          <ns2:Size>5 Pound</ns2:Size>
          <ns2:SmallImage>
            <ns2:URL>http://ecx.images-amazon.com/images/I/51MRGj4bbuL._SL75_.jpg</ns2:URL>
            <ns2:Height Units="pixels">75</ns2:Height>
            <ns2:Width Units="pixels">50</ns2:Width>
          </ns2:SmallImage>
          <ns2:Studio>Optimum Nutrition</ns2:Studio>
          <ns2:Title>Optimum Nutrition 100% Whey Gold Standard, Double Rich Chocolate, 5 Pound</ns2:Title>
        </ns2:ItemAttributes>
      </AttributeSets>
      <Relationships>
        <VariationParent>
          <Identifiers>
            <MarketplaceASIN>
              <MarketplaceId>ATVPDKIKX0DER</MarketplaceId>
              <ASIN>B00OXVNR66</ASIN>
            </MarketplaceASIN>
          </Identifiers>
        </VariationParent>
      </Relationships>
      <SalesRankings>
        <SalesRank>
          <ProductCategoryId>health_and_beauty_display_on_website</ProductCategoryId>
          <Rank>35</Rank>
        </SalesRank>
        <SalesRank>
          <ProductCategoryId>6973717011</ProductCategoryId>
          <Rank>1</Rank>
        </SalesRank>
        <SalesRank>
          <ProductCategoryId>3764441</ProductCategoryId>
          <Rank>4</Rank>
        </SalesRank>
      </SalesRankings>
    </Product>
  </GetMatchingProductResult>
  <ResponseMetadata>
    <RequestId>1420dfd3-997d-4db9-bc81-a9a4cb665188</RequestId>
  </ResponseMetadata>
</GetMatchingProductResponse>

1 个答案:

答案 0 :(得分:1)

创建DOM并加载XML:

$dom = new DOMDocument();
$dom->loadXml($xml);

为它创建一个DOMXpath对象并为命名空间注册前缀/别名:

$xpath = new DOMXpath($dom);
$xpath->registerNamespace(
  'p', 'http://mws.amazonservices.com/schema/Products/2011-10-01'
);
$xpath->registerNamespace(
  'pd', 'http://mws.amazonservices.com/schema/Products/2011-10-01/default.xsd'
);

使用XPath表达式获取节点列表并迭代它们:

foreach ($xpath->evaluate('//p:Product') as $product) {
  ...
}

使用XPath表达式获取上下文节点的实际值。已注册的前缀在内部解析为命名空间:

var_dump(
 [
   'MarketplaceId' => $xpath->evaluate(
     'string(p:Identifiers/p:MarketplaceASIN/p:MarketplaceId)', $product
   ),
   'Brand' => $xpath->evaluate(
     'string(p:AttributeSets/pd:ItemAttributes/pd:Brand)', $product
   )
 ]
);