<ITEMS>
<ITEM ItemID="XY">
<ItemSearchName />
<ITEMDESCRIPTION>
<DESCRIPTION descriptionType="T" descriptionTypeTitle="Short" languageId="1" language="English">English description</DESCRIPTION>
<DESCRIPTION descriptionType="T" descriptionTypeTitle="Short" languageId="2" language="France">Fance description</DESCRIPTION>
</ITEMDESCRIPTION>
<ItemType>B</ItemType>
<ItemDepartment />
<ITEMDIMENSIONS>
<ItemDimensionUOM>m</ItemDimensionUOM>
</ITEMDIMENSIONS>
<ItemGrossWeihgt>0.00</ItemGrossWeihgt>
</ITEM>
</ITEMS>
这是我使用simplexml方法解析的XML文件的示例。我用这段代码读了ItemID属性值(只是一个例子):
$item->attributes()->ItemID
我的问题是,如何访问DESCRIPTION属性languageId = 1?
下的DESCRIPTION我可以用foreach做到这一点:
foreach ($item->ITEMDESCRIPTION->DESCRIPTION as $desc) {
if ($desc['languageId'] == '1') {
echo "<td>" . $desc . "</td>";
}
}
但我不想使用foreach。
另一种可能性是:
$desc2 = $item->ITEMDESCRIPTION->DESCRIPTION[1];
但这只是第一个描述,而不是属性languageId = 1的描述。
感谢您的任何建议!
答案 0 :(得分:0)
您还可以使用xpath
来获取特定值。例如:
$xml_string = '<ITEMS> <ITEM ItemID="XY"> <ItemSearchName /> <ITEMDESCRIPTION> <DESCRIPTION descriptionType="T" descriptionTypeTitle="Short" languageId="1" language="English">English description</DESCRIPTION> <DESCRIPTION descriptionType="T" descriptionTypeTitle="Short" languageId="2" language="France">Fance description</DESCRIPTION> </ITEMDESCRIPTION> <ItemType>B</ItemType> <ItemDepartment /> <ITEMDIMENSIONS> <ItemDimensionUOM>m</ItemDimensionUOM> </ITEMDIMENSIONS> <ItemGrossWeihgt>0.00</ItemGrossWeihgt> </ITEM></ITEMS>';
$xml = simplexml_load_string($xml_string);
$value = $xml->xpath('//ITEMDESCRIPTION/DESCRIPTION[@languageId="1"]')[0];
echo (string) $value; // English description
或者只是简单的预告:
foreach($xml->ITEM->ITEMDESCRIPTION->DESCRIPTION as $desc) {
if($desc->attributes()['languageId'] == 1) {
echo (string) $desc; // English description
}
}