Reputation: 131
I am using XPATH (with PHP) to retrieve XML data based on the XML attributes. The XML structure is like this:
<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".
$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. They test the XML element <shipping>
which has TWO attributes - "cost" and "carrier".
$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!
Upvotes: 1
Views: 150
Reputation: 6625
In your xpath
-expressions, you need to select <product>
and keep the condition in []
:
/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.
see it working: https://eval.in/128925
Upvotes: 1
Reputation: 78671
You should use
/products/product/shipping[@carrier='$shippingCarrier']
because shipping
is not a direct child of products
.
You could also look for all descendants like this:
/products//shipping[@carrier='$shippingCarrier']
Upvotes: 1