skip to Main Content

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.

3

Answers


  1. Chosen as BEST ANSWER

    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.


  2. <?php
    // Load the XML file
    $xml = simplexml_load_file('your_xml_file.xml');
    
    // Iterate through each "item" element
    foreach ($xml->item as $item) {
        // Output the description and city
        echo $item->description . ' in ' . $item->city . '<br>';
    }
    ?>
    
    Login or Signup to reply.
  3. Unlike php, xpath indexing start from "1".

    So either of these should get you only the first trip:

    #indexing is indicated inside the xpath expression so it starts with 1:
    $items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]][1]');
    

    or

    #indexing is indicated outside the xpath expression so it's handled by php and  starts with 0:
    $items = $xml->xpath('//item[city[contains(.,"London")] and description[contains(.,"Trip")]]')[0];
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search