-1
foreach($resultXML->products->children() as $product) { 
    echo "<p><a href=".$product->{'buy-url'}.">".$product->{'advertiser-name'}." - ".$product->price."</a></p>
    <p>".$product->{'description'}."</p>"; 

}

Suppose I wanted to screen out the ones that had the same title, and only display the first title that appears in the return results.

I'm not working with my own database, this is all about what's displayed.

2 Answers2

0

I suppose the easiest way would be to keep track of the titles in an array, and checking it each iteration.

$titles = array();
foreach($resultXML->products->children() as $product) {
    if (in_array($product->title, $titles) continue;
    $titles[] = $product->title;
    echo "<p><a href=".$product->{'buy-url'}.">".$product->{'advertiser-name'}." - ".$product->price."</a></p>
    <p>".$product->{'description'}."</p>"; 
}

Assuming that the title is contained in $product->title. You could do something fancier through array functions, but I don't see a reason to make a simple problem complicated.

Joel Hinz
  • 24,719
  • 6
  • 62
  • 75
0

You have not provided any exemplary XML, so given for

<?xml version="1.0" encoding="UTF-8"?>
<example>
    <products>
        <product>
            <title>First Product</title>
            <advertiser-name>First Name</advertiser-name>
        </product>
    </products>
    <products>
        <product>
            <title>Second Product</title>
            <advertiser-name>First Name</advertiser-name>
        </product>
    </products>
    <products>
        <product>
            <title>Third Product</title>
            <advertiser-name>Second Name</advertiser-name>
        </product>
    </products>
</example>

You want to get all product elements with an advertiser-name that is not an advertiser-name of all preceding product elements.

So for the XML above, that would be the 1st and 3rd product element.

You can write that down as an XPath expression:

/*/products/product[not(advertiser-name = preceding::product/advertiser-name)]

And as PHP code:

$xml  = simplexml_load_string($buffer);

$expr = '/*/products/product[not(advertiser-name = preceding::product/advertiser-name)]';

foreach ($xml->xpath($expr) as $product) {
    echo $product->asXML(), "\n";
}

This produces the following output:

<product>
            <title>First Product</title>
            <advertiser-name>First Name</advertiser-name>
        </product>
<product>
            <title>Third Product</title>
            <advertiser-name>Second Name</advertiser-name>
        </product>

So one answer to your question therefore is: Only query those elements from the document you're interested in. XPath can be used for that with SimpleXMLElement.

Related questions:

Community
  • 1
  • 1
hakre
  • 193,403
  • 52
  • 435
  • 836