[英]PHP - using XPATH to reference XML element with 2 attributes
I am using XPATH (with PHP) to retrieve XML data based on the XML attributes. 我正在使用XPATH(与PHP一起)来基于XML属性检索XML数据。 The XML structure is like this: XML结构如下:
<products>
<product category="Desktop">
<name> Dell Desktop (d)</name>
<price>499.99</price>
<shipping cost="10.99" carrier="UPS" />
</product>
</products>
This code works fine, as it tests the XML element <product>
which only has ONE attribute - named "category". 该代码可以正常工作,因为它可以测试XML元素<product>
,该元素仅具有一个属性-名为“类别”。
$productVar = "Desktop";
$x_path = $XMLproducts->xpath("/products/product[@category='$productVar']");
foreach($x_path as $Product) {
echo $Product->name . " - " . $Product->price . "<br>";
}
But the next two foreach loops are NOT displaying anything. 但是接下来的两个foreach循环不显示任何内容。 They test the XML element <shipping>
which has TWO attributes - "cost" and "carrier". 他们测试具有两个属性的XML元素<shipping>
-“成本”和“运营商”。
$shippingCarrier = "UPS";
$xpath = $XMLproducts->xpath("/products/shipping[@carrier='$shippingCarrier']");
foreach($xpath as $Product) {
echo $Product->name . " - " . $Product->price . "<br>";
}
$shippingCost = "UPS";
$xpath = $XMLproducts->xpath("/products/shipping[@cost='$shippingCost']");
foreach($xpath as $Product) {
echo $Product->name . " - " . $Product->price . "<br>";
}
Any advice? 有什么建议吗? Thanks! 谢谢!
You should use 你应该用
/products/product/shipping[@carrier='$shippingCarrier']
because shipping
is not a direct child of products
. 由于shipping
是不是一个直接子products
。
You could also look for all descendants like this: 您还可以像这样查找所有后代:
/products//shipping[@carrier='$shippingCarrier']
In your xpath
-expressions, you need to select <product>
and keep the condition in []
: 在xpath
-expressions中,您需要选择<product>
并将条件保留在[]
:
/products/product[shipping/@carrier='$shippingCarrier']
and... 和...
/products/product[shipping/@cost='$shippingCost']
Moreover, you need to set your $shippingCost
to "10.99"
instead of "UPS"
to select data. 此外,您需要将$shippingCost
设置为"10.99"
而不是"UPS"
来选择数据。
see it working: https://eval.in/128925 看到它正常工作: https : //eval.in/128925
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.