Search code examples
phpxpathsimplexml

Selecting elements based on 2 child elements


Here is part of my XML file

<item>
    <title>The product</title>
    <description>Product description</description>
    <oldprice>350</oldprice>
    <price>250</price>
    <category>KIDS DISCOUNT</category>
    <link>page.htm</link>
    <img>product.jpg</img>
</item>

If I want products discount, it's OK :

<?php  
        $xml   = simplexml_load_file('file.xml');
        $items = $xml->xpath('//item/category[contains(.,"DISCOUNT")]/.. ');
        foreach($items as $item){
            echo '<p>...</p>';
        }
?>

If I want products less than 300, it' OK :

<?php  
    $xml   = simplexml_load_file('file.xml');
    $items = $xml->xpath('//item/price[.<300]/.. ');
    foreach($items as $item){
        echo '<p>...</p>';
?>

But if I want both, I can't... I tried this, but it's wrong :

<?php  
    $xml   = simplexml_load_file('file.xml');
    $items = $xml->xpath('//item/price[.<300] [//item/category[contains(.,"DISCOUNT")]]/.. ');
    foreach($items as $item){
        echo '<p>...</p>';
?>

Somebody can help me ?


Solution

  • To get item that either has price less than 300, or has category containing text 'DISCOUNT' :

    //item[category[contains(.,"DISCOUNT")] or price[. < 300]]
    

    If, one item always has maximum one category and one price, the above expression can be simplified further to :

    //item[contains(category,"DISCOUNT") or price < 300]
    

    If you want selected item to fulfill both conditions instead, then simply replace the or with and.