JackTheJack
JackTheJack

Reputation: 187

Showing Two elements from XML file

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?

Upvotes: 1

Views: 178

Answers (2)

salathe
salathe

Reputation: 51950

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
}

Upvotes: 1

dfsq
dfsq

Reputation: 193271

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

Upvotes: 1

Related Questions