如何获得XML第二个孩子

时间:2013-03-27 04:48:02

标签: php xml

有人可以帮助我获得以下xml的第二个孩子:

<?xml version="1.0" encoding="UTF-8"?>
<GetItemResponse xmlns="urn:ebay:apis:eBLBaseComponents">
  <Timestamp>2013-03-27T03:39:01.575Z</Timestamp>
  <Ack>Success</Ack>
  <Version>815</Version>
  <Build>E815_CORE_API_15855340_R1</Build>
    <item>
    <ApplicationData>881030.B.0000</ApplicationData>
    <AutoPay>false</AutoPay>
    <BuyerProtection>ItemEligible</BuyerProtection>
    <BuyItNowPrice currencyID="USD">0.0</BuyItNowPrice>
    <Country>US</Country>
    <Currency>USD</Currency>
    <GiftIcon>0</GiftIcon>
    <HitCounter>RetroStyle</HitCounter>
    <ItemID></ItemID>
    <ListingDetails>
      <Adult>false</Adult>
      <BindingAuction>false</BindingAuction>
      <CheckoutEnabled>true</CheckoutEnabled>
      <ConvertedBuyItNowPrice currencyID="USD">0.0</ConvertedBuyItNowPrice>
     <ShippingServiceOptions>
            <ShippingService>UPSGround</ShippingService>
            <ShippingServiceCost currencyID="USD">9.99</ShippingServiceCost>
     </ShippingServiceOptions>
     <InternationalShippingServiceOption>
            <ShippingService>StandardInternational</ShippingService>
            <ShippingServiceCost currencyID="USD">39.99</ShippingServiceCost>
     </InternationalShippingServiceOption>
    <item>

我正在使用for for循环遍历所有项目($ item作为$ item)。我需要从ShippingServiceOptions和InternationalShippingServiceOption获取ShippingServiceCost。

我想执行以下操作但不起作用:

//for ShippingServiceOptions
$item->getElementsByTagName('ShippingServiceCost')->item(0)->nodeValue;

//for InternationalServiceOptions
$item->getElementsByTagName('ShippingServiceCost')->item(1)->nodeValue;

1 个答案:

答案 0 :(得分:0)

编辑

因为你发布了完整的XML,php xml遍历将如下所示:

$xml = simplexml_load_string($response);
foreach($xml->item->ListingDetails as $child) {
    foreach($child->children() as $option) {
        if(isset($option->ShippingServiceCost)){
            echo $option->getName() . ": " . $option->ShippingServiceCost . "<br>";
        }
    }
}

您发布的XML有错误,以后请在发布前验证,以便我们无需修复错误:)


如果你有PHP 5 +,你可以使用simplexml来解析你的xml。 此外,您需要关闭“item”xml标记。

然后代码变为:

<?php
    $xml = simplexml_load_file("test.xml");
    foreach($xml->children() as $child) {
        echo $child->getName() . ": " . $child->ShippingServiceCost . "<br>";
    }
?>

xml:

<item>
 <ShippingServiceOptions>
        <ShippingService>UPSGround</ShippingService>
        <ShippingServiceCost currencyID="USD">9.99</ShippingServiceCost>
 </ShippingServiceOptions>
 <InternationalShippingServiceOption>
        <ShippingService>StandardInternational</ShippingService>
        <ShippingServiceCost currencyID="USD">39.99</ShippingServiceCost>
 </InternationalShippingServiceOption>
</item>

输出:

ShippingServiceOptions: 9.99
InternationalShippingServiceOption: 39.99