2017-07-28 110 views
1

我試圖獲取另一個標記內的標記的內容以及指定ID標記。源是以下XML響應:如何使用php獲取父標記的子標記的內容使用php

XML響應是這裏

<PricePlans> 
    <PricePlan> 
     <Description>Check Email</Description> 
     <ID>1</ID> 
     <Price>2</Price> 
     <Time>900</Time> 
    </PricePlan> 
    <PricePlan> 
     <Description>High Speed</Description> 
     <ID>2</ID> 
     <Price>5</Price> 
     <Time>3600</Time> 
    </PricePlan> 
</PricePlans> 

我的PHP代碼是在這裏:

echo "Desc" ." ".$xml->PricePlan->Description ."</br>"; 

此代碼給我的第一個內容「描述」標籤(檢查電子郵件),但我想要描述具有特定「ID」標籤的價格計劃(例如ID 2 - 「高速」) xml響應可能有更多「Pr icePlan「標籤,但每個在」ID「標籤中都有唯一的值。

回答

1

您可以訪問它們一樣的陣列:

echo($xml->PricePlan[0]->Description); 
//Check Email 
echo($xml->PricePlan[1]->Description); 
//High Speed 

foreach ($xml->PricePlan as $pricePlan) { 
    echo($pricePlan->Description); 
} 
//Check Email 
//High Speed 

如果需要的價值由ID查找元素,您可以使用XPath:

$el = $xml->xpath('/PricePlans/PricePlan/ID[text()=2]/..'); 
1

舉一個元件與說明一個特定的ID你可以使用xpath。

$id = 2; 

// xpath method always returns an array even when it matches only one element, 
// so if ID is unique you can always take the 0 element 
$description = $xml->xpath("/PricePlans/PricePlan/ID[text()='$id']/../Description")[0]; 

echo $description; // this echoes "High Speed" 
相關問題