2017-07-28 113 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" 
相关问题