0

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:

<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 shirt12.php, I would need to fetch just the info from <product id="023"> and <product id="024"> since those contain my information for the "Shirt 12" styles.

Using simplexml I'm able to fetch the data of one <product> using this code:

foreach ($products->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.

cryssybee
  • 15
  • 1
  • 5

3 Answers3

1

Things can be easier with XPath:

$xml=simplexml_load_string(<<<XML
<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>
XML
);
foreach($xml->xpath('//product[starts-with(name/text(),"Shirt 12")]') as $product)
{
    echo $product->name;
    echo "\n";
    echo $product->price;
    echo "\n";
    echo $product->color;
    echo "\n\n";
}

Online Demo

Update:

If you need to fetch by id, just change the XPath:

foreach($xml->xpath('//product[@id="023" or @id="024"]') as $product)

Online Demo that also demonstrate how to fetch the ID attribute.

Passerby
  • 9,715
  • 2
  • 33
  • 50
  • Can you show me how I'd do this JUST using the id numbers in ``? Unfortunately my XML file doesn't have each product named as nicely as my example. Also the product id numbers will be used as corresponding id numbers for the `
    ` or `
  • ` tags I use to display each individual product style.
– cryssybee May 24 '13 at 16:01