rand()打乱xml输出


rand() shuffle xml output

我创建了一个包含许多项的XML文件,如下例所示:

<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <id>http://www.example.com/index.php?pagina=video-categories</id>
  <title><![CDATA[Example.com Categories RSS]]></title>
  <author>
  <name>Example.com</name>
  <email>email@example.com</email>
  </author>
  <updated></updated>
  <link rel="alternate" href="http://www.example.com/categories"/>
  <subtitle><![CDATA[HQ example videos in any category]]></subtitle>
  <rights>Copyrights reserved. Feel free to use the embed function.</rights>
    <item>
    <categoryname><![CDATA[100 Latest Videos]]></categoryname>
    <shortcategoryname><![CDATA[100 New Sex Clips]]></shortcategoryname>
    <categoryurl>http://www.example.com/1.html</categoryurl>
    <categoryimage>http://www.example.com/12347.jpg</categoryimage>
    </item>
    <item>
    <categoryname><![CDATA[100 Latest Videos]]></categoryname>
    <shortcategoryname><![CDATA[100 New Sex Clips]]></shortcategoryname>
    <categoryurl>http://www.example.com/2.html</categoryurl>
    <categoryimage>http://www.example.com/12346.jpg</categoryimage>
    </item>
    <item>
    <categoryname><![CDATA[100 Latest Videos]]></categoryname>
    <shortcategoryname><![CDATA[100 New Sex Clips]]></shortcategoryname>
    <categoryurl>http://www.example.com/3.html</categoryurl>
    <categoryimage>http://www.example.com/12345.jpg</categoryimage>
    </item>
    ... and more items ...
    </feed>

我有下面的代码,作为输出来自XML文件的所有链接

     <?php
     $html = ""; // var full of emptyness
     $url = "http://www.example.com/categories.xml";
     $xml = simplexml_load_file($url);
     for($i = 0; $i < 35; $i++){ // Number of category here, I use a lower number at this moment... 
     $categoryname = $xml->item[$i]->categoryname;
     $shortcategoryname = $xml->item[$i]->shortcategoryname;
     $categoryurl = $xml->item[$i]->categoryurl;
     $html .= '<a class="purplewidebutton" href="' . $categoryurl . '" title="' . $categoryname . '">' . $shortcategoryname . '</a>';
     }
     echo $html;
     ?>

我只想显示6个链接,并从XML提要中制作它们的位置雷达罩。我希望有来自xml项目的随机链接。我应该添加或更改什么?我应该使用rand()shuffle()来回显6个随机链路吗?

php代码是我现在用来回复一些链接的,但它不是随机的。。。

$xml->item是一个数组,所以shuffle是它,然后得到第一个6,类似于:

shuffle($xml->item);
foreach(array_slice($xml->item, 0, 6) as $item) {
    $categoryname = $item->categoryname;
    $shortcategoryname = $item->shortcategoryname;
    $categoryurl = $item->categoryurl;
    $html .= '<a class="purplewidebutton" href="' . $categoryurl . '" title="' . $categoryname . '">' . $shortcategoryname . '</a>';
}
echo $html;

或者使用当前代码,您可以将HTML存储在循环中的数组中:

$html[] = '<a class="purplewidebutton" href="' . $categoryurl . '" title="' . $categoryname . '">' . $shortcategoryname . '</a>';

循环后:

shuffle($html);
echo implode("'n", array_slice($html, 0, 6));