Search code examples
phpxpathsimplexml

Simplexml : xpath with three conditions


I have a xml file like this :

<rss version="2.0" xmlns:atom="https://www.w3.org/2005/Atom">
<channel>
<item>
    <city>London</city>
    <description>Trip</description>
    <link>page.php</link>
    <img>img.jpg</img>
</item>
<item>
    <city>London</city>
    <description>Trip</description>
    <link>page.php</link>
    <img>img.jpg</img>
</item>
<item>
    <city>Paris</city>
    <description>Trip</description>
    <link>page.php</link>
    <img>img.jpg</img>
</item>
.
.
</channel>
</rss>

If I want to select TRIP in LONDON, I do that :

<?php
$xml   = simplexml_load_file('file.xml');
$items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]');
foreach($items as $item){
echo ' txt ';
}
?>

If I want to select ONLY the first TRIP in LONDON, I do that :

<?php
$xml   = simplexml_load_file('file.xml');
$items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]')[0];
foreach($items as $item){
echo ' txt ';
}
?>

I try also 1 instead of 0, and this

[position()=0]

it does not work.

What's wrong ?

I keep looking. I have made several tests only with the position filter, for example :

<?php  
$xml   = simplexml_load_file('file.xml');
$items = $xml->xpath('//(/item)[1]');
foreach($xml->channel->item as $item){
echo '<div>....</div>';
}
?>

And it doesn't work.

I think I have a problem with this part, but I don't see where.


Solution

  • I found this way (to find only the first one) :

    $xml   = simplexml_load_file('file.xml');
        $i = 0;
        $nb_affichage = 1;
        $items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]');
        foreach($xml->channel->item as $item){
        echo '<div> txt </div>';
        if(++$i>=$nb_affichage)
        break;
        }
    

    It's definitely not the best, but it works. If anyone has a better idea, I'm still interested.