Link to home
Start Free TrialLog in
Avatar of Cristina Delgado
Cristina DelgadoFlag for Germany

asked on

Get random item from XML with PHP

Hey!

I'd like some help with a project I'm working on right now.

I have an XML Product Feed, and I have created a viewer with php. For now I get the first three products to appear. My goal is that with every page load/impression new random products from the feed appear.


Here's my code for now:

<div id="wrapper">
<div id="feed_div">
<?php $rss = simplexml_load_file('http://rs237033.rs.hosteurope.de/tectumedia/Esprit/Feed.xml');


echo '<h2>'. $rss->channel->title . '</h2>';
echo '<a href="https://www.esprit.de/sale/damenmode"><img style="width: 40%; height: auto; margin-left:-20px;" src="https://www.esprit.de/on/demandware.static/Sites-EspritCentralHub-Site/-/default/dw4e93f4fe/images/logo-colored.svg" alt="Logo"/></a> <div style="display:inline-block; text-align:right; margin-left:90px; background-color:black; padding:5px 10px; font-size:12px;"><a style="color:white; text-decoration:none;" href="https://www.esprit.de/sale/damenmode">Jetzt shoppen!</a></div>';
   
shuffle ($rss);
foreach ($rss->channel->item as $item) 
{
 echo '<div style="display:inline-block; width:33.33%;flex:1; text-align: center;">';
 echo "<p class='desc' style='text-align:center; margin:0;'><a href='". $item->link ."'>" . $item->description . '</a></p>';
 echo '<p class="title"><a href="'. $item->link .'">' . $item->title . "</a></p>";
 echo '</div>';
} 
?> 

</div>
</div>

Open in new window


Avatar of Chris Harte
Chris Harte
Flag of United Kingdom of Great Britain and Northern Ireland image

I have written an article on this very subject. If it does not provide you with what you need, please let me know.
https://www.experts-exchange.com/articles/11342/Reading-XML-Namespaces-using-PHP-Without-regex.html
Avatar of Cristina Delgado

ASKER

Hi Chris,

your article was actually really useful for another question that I had but it doesn't contain the answer to display random products from the feed (sort of different order or rotation) on every page load/impression.
Hey Cristina,

Couple of ways to approach this. Here's one idea:

$rss = simplexml_load_file("http://rs237033.rs.hosteurope.de/tectumedia/Esprit/Feed.xml");

// Get all the 'item' nodes into an array
$items = $rss->xpath('//item');

// randomly pick 3 'keys' from the $items array
$randKeys = array_rand($items, 3);

// loop over the 3 random keys
foreach ($randKeys as $key):
    echo $items[$key]->title;
endforeach;

Open in new window

I realised that after I posted the answer. You are going to have to read the whole rss every time and count the number of entries. Then generate three random numbers between 1 and the total number of entries and directly access that numbered element in the rss.
 
(I am at work at the moment and don't have access to my php server, so no code yet.)
ASKER CERTIFIED SOLUTION
Avatar of Ferruccio Accalai
Ferruccio Accalai
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Ferruccio,

thanks for your help. The code you provided is taking one product and repeating it three times, also I'd like the products to be different on every page load.
Are you sure? My test shows 3 different products at any page refresh.
http://95.255.239.18/res.php
You are completely right! thank you so much for your help. 
Did you not try my code - it will give you exactly what you need !
Hello again everyone,
Would it be possible to get the same result but with html instead of php?
Hi Cristina,

No. HTML is NOT a programming language so you can't do what you want. 
Hi Chris, I understand. I have this for now but I'm stuck with getting 3 random items on every page load:
I should be using math random but not really sure how to introduce it here.
let url = 'http://rs237033.rs.hosteurope.de/tectumedia/Esprit/Feed_2.xml';
  const textarea = document.querySelector('#feed-textarea > ul');

  const date = new Date();
  document.querySelector('#date').innerHTML = date.toDateString();
    
    feednami.load(url)
    .then(feed => {
      textarea.value = ''
      console.log(feed);
      for(let entry of feed.entries){
          //create a list element
          
          let li = document.createElement('li');
          //add HTML content to list items
          li.innerHTML = `<h4><p style='text-align:center; margin:0;'><a href="${entry.link}">${entry.description}</a><a href="${entry.link}">${entry.title}</a></p></h4>`;
          //append HTML content to list 
          textarea.appendChild(li);
      }
      
    });

Open in new window

Hey Cristina,

Basically, you'll need to randomly sort the array (feed.entries) and then pick the first 3:

.then(feed => {
  const entries = feed.entries.sort(() => 0.5 - Math.random()); // randomly sort the array
  let selected = entries.slice(0, 3); // now pick the first 3

  for(let entry of selected){
    let li = document.createElement('li');
    li.innerHTML = `<h4><p style='text-align:center; margin:0;'><a href="${entry.link}">${entry.description}</a><a href="${entry.link}">${entry.title}</a></p></h4>`;
    textarea.appendChild(li);
  }
});

Open in new window


This question has already been closed off, and was tagged as PHP, so if you're still stuck, it makes sense to open a new one.