1
votes

The file can be seen on the following URL: #

The above XML file consists of two elements which I want to be shown in order which are the "product" and "offer".

I use SimpleXML to load the XML feed.

$text = simplexml_load_file('feed.xml');

I also use foreach to show the data from the file

foreach ($text->categories->category->items->product as $product) {}

How is it possible to show the "product" and "offer" from the XML file using a for each statement or any other method?

2
You are saying that you "show the data from the file". So what do you mean "How is it possible to show the "product"" if you already show them? - dfsq
By that I mean how can I show both pieces of data, instead of showing just one? I have come across XPath however not sure if it can be used in this case. - JackTheJack
XPath makes reading XML data very easy. But explain exactly how you want to display your data, because now it's not clear how product items relate offer. - dfsq
The product and offer consist of different pieces of information about products returned in the XML file. Currently I am currently only able to show products or offer, where I want to display them both in any order. For example display the amount of products and offers from the feed in order. - JackTheJack
Currently I display the data from the product element via 'print $text->categories->category->items->product->name;' and via the offer element I would use 'print $text->categories->category->items->product->offers->offer->name;' However I only can use product or offer so that's why I want to use XPath to show them both. - JackTheJack

2 Answers

1
votes

Although I'm still don't really get what you would like to obtain I will post some examples of how to deal with this XML via xPath.

First of all select all product and offer nodes:

$xml = simplexml_load_file('feed.xml');

// Make sure to register custom namespace
$xml->registerXPathNamespace('ns', 'urn:types.partner.api.url.com');

$products = $xml->xpath('//ns:product');
$offers   = $xml->xpath('//ns:offer');

echo count($products); // Number of all product nodes
echo count($offers); // Number of offer nodes

Basic iteration:

foreach ($products as $product) {
    //echo '<pre>'; print_r($product); echo '</pre>';
    echo '<pre>'; echo $product->name . ', ' . $product->minPrice; echo '</pre>';
}
1
votes

Does <items> only ever contain <product> and <offer> elements? If so:

foreach ($text->categories->category->items->children() as $product_or_offer) {
    // Do something
}

See http://php.net/simplexmlelement.children


If you want to be explicit about only ever getting the product/offer elements, a simple XPath expression could be employed.

$items = $text->categories->category->items;
$items->registerXPathNamespace('so', 'urn:types.partner.api.url.com');
foreach ($items->xpath('so:offer|so:product') as $product_or_offer) {
    // Do something
}