Question

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>
Was it helpful?

Solution

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>";
}

OTHER TIPS

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>";
      }
   }
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top