1

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!

2 Answers 2

1

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 $shippingCostto "10.99" instead of "UPS" to select data.

see it working: https://eval.in/128925

Sign up to request clarification or add additional context in comments.

Comments

1

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']

1 Comment

Thanks. The coding you provided is correct! However, for some odd reason, in the echo statement in the foreach loop, .... echo $Product->name . " - " . $Product->price . "<br>"; ..... the only thing that is displaying is the hyphen.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.