PHP - Fetch data from specific child elements in XML file

admin

Administrator
Staff member
I'm a PHP/developing novice and I haven't been able to find a tutorial with a solution to this particular problem.

I have a XML file from an API with product information for an online store. Each physical product has multiple "styles" that need to be listed on the same page. I want to do that using their id numbers.

Here's a simplified version of what my feed looks like:

Code:
<products>
  <product id="001">
    <name>Shirt 1 - Women's</name>
    <price>12.00</price>
    <color>blue</color>
  </product>

  <product id="002">
    <name>Shirt 1 - Men's</name>
    <price>12.00</price>
    <color>red</color>
  </product>
   ...
  <product id="023">
    <name>Shirt 12 - Women's</name>
    <price>15.00</price>
    <color>purple</color>
  </product>

  <product id="024">
    <name>Shirt 12 - Men's</name>
    <price>15.00</price>
    <color>yellow</color>
  </product>

</products>

So on
Code:
shirt12.php
, I would need to fetch <strong>just</strong> the info from
Code:
&lt;product id="023"&gt;
and
Code:
&lt;product id="024"&gt;
since those contain my information for the "Shirt 12" styles.

Using simplexml I'm able to fetch the data of one
Code:
&lt;product&gt;
using this code:

Code:
foreach ($products-&gt;product as $product) {
if ($product['id'] == '024') { 
  //display data using some code
  }
}

I have no clue how I'd do this for two ore more. If it can be done with simplexml, that would be great because I'm most familiar it. But if I need to use a different XML parsing method, I'm open to that as well, however it needs to be compatible with wordpress.