0

Using the simplexml_load_file method, I am trying to retrieve and display the text of all name elements (from an XML file below) that have an attribute named "type' with the value of 'tablet.' This foreach loop is only displaying the value of the first element. Any advice? Thanks!

$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product->attributes() as $a => $b) {
  $i = 0;
  if ($b == "Tablet") {
    echo $XMLproducts->product[$i]->name;
    echo "<br>";
  }
}

Here is the XML file:

<products>

  <product type="Desktop">
   <name>Desktop 1</name>
  </product>

  <product type="Tablet">
    <name>Ipad 1</name>
  </product>

  <product type="Desktop">
    <name>Desktop 2</name>
  </product>

  <product type="Tablet">
    <name>Ipad 2</name>
  </product>

</products>
2
  • You'll need to do 2 loops: foreach($XMLproducts->product as $product){ foreach($product->attributes() as $a => $b){ if($b=='Tablet') echo $product->name;}}. (or use 1 Xpath: /product[@type="Tablet"]/name). Commented Mar 20, 2014 at 0:05
  • 1
    Look at using php.net/manual/en/simplexmlelement.xpath.php, it is a godsend Commented Mar 20, 2014 at 0:12

2 Answers 2

1

As Scuzzy mentioned in the comments, using SimpleXMLElement::xpath simplifies the solution:

foreach ($XMLproducts->xpath('/products/product[@type="Tablet"]/name') as $name) {
    echo $name , "<br>";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Try this

 $XMLproducts = simplexml_load_file("products.xml");
 foreach($XMLproducts->products->product as $product) {
   foreach ($product->attributes() as $a => $b) {
      $i = 0;
      if ($b == "Tablet") {
         echo $XMLproducts->product[$i]->name;
         echo "<br>";
      }
   }
 }

Comments

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.