質問

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>
役に立ちましたか?

解決

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

他のヒント

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>";
      }
   }
 }
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top