Php 使用javascript从xml文件加载一系列随机图像

Php 使用javascript从xml文件加载一系列随机图像,php,javascript,xml,Php,Javascript,Xml,这是到目前为止我所拥有的代码,目前它使用javascript从xml文件加载所需的信息。我将其设置为循环4次以选择4个图像,但这些显然只是xml文件中的前4个图像 <script> if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5

这是到目前为止我所拥有的代码,目前它使用javascript从xml文件加载所需的信息。我将其设置为循环4次以选择4个图像,但这些显然只是xml文件中的前4个图像

<script>
if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","include/photoLibrary.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

var x=xmlDoc.getElementsByTagName("photo");
    for (i=0; i<4; i++)
    { 
    document.write('<a href="');
    document.write(x[i].getElementsByTagName('path')[0].childNodes[0].nodeValue);
    document.write('" class="lytebox" data-lyte-options="group:vacation" data-title="');
    document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
    document.write('"><img src="');
    document.write(x[i].getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
    document.write('" alt"');
    document.write(x[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
    document.write('"/></a>');                      
    }
</script>
有没有人知道从xml文件中随机选择4个无重复图像的最佳方法

<script>
if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
    }
else
    {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET","include/photoLibrary.xml",false);
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;

var x=xmlDoc.getElementsByTagName("photo");
    for (i=0; i<4; i++)
    { 
    document.write('<a href="');
    document.write(x[i].getElementsByTagName('path')[0].childNodes[0].nodeValue);
    document.write('" class="lytebox" data-lyte-options="group:vacation" data-title="');
    document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
    document.write('"><img src="');
    document.write(x[i].getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
    document.write('" alt"');
    document.write(x[i].getElementsByTagName('title')[0].childNodes[0].nodeValue);
    document.write('"/></a>');                      
    }
</script>

if(window.XMLHttpRequest)
{//IE7+、Firefox、Chrome、Opera、Safari的代码
xmlhttp=新的XMLHttpRequest();
}
其他的
{//IE6、IE5的代码
xmlhttp=新的ActiveXObject(“Microsoft.xmlhttp”);
}
open(“GET”,“include/photoLibrary.xml”,false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName(“照片”);
对于(i=0;i您可以添加

x = Array.prototype.slice.call(x).sort( function () {
    return Math.random() > 0.5 ? 1 : -1 
} );
紧接着

var x = xmlDoc.getElementsByTagName("photo");
这将创建一个随机排序的元素数组,其中前四个元素将由for循环迭代

编辑

请注意,此方法不会对数组进行适当的随机洗牌,请参阅,我不推荐使用此方法。

您可以添加

x = Array.prototype.slice.call(x).sort( function () {
    return Math.random() > 0.5 ? 1 : -1 
} );
紧接着

var x = xmlDoc.getElementsByTagName("photo");
这将创建一个随机排序的元素数组,其中前四个元素将由for循环迭代

编辑


请注意,此方法不会对数组进行适当的随机洗牌,请参阅,我不推荐使用此方法。

在PHP中,解析文件的方式如下:

index.php

<?php
$doc = new DOMDocument();
  $doc->load( 'book.xml' );

  $books = $doc->getElementsByTagName( "book" );
  foreach( $books as $book )
  {
  $authors = $book->getElementsByTagName( "author" );
  $author = $authors->item(0)->nodeValue;

  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;

  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;

  echo "$title - $author - $publisher\n";
  }?>
getElementsByTagName(“book”);
foreach($books作为$book)
{
$authors=$book->getElementsByTagName(“作者”);
$author=$authors->item(0)->nodeValue;
$publisher=$book->getElementsByTagName(“publisher”);
$publisher=$publisher->item(0)->nodeValue;
$titles=$book->getElementsByTagName(“title”);
$title=$titles->item(0)->nodeValue;
回显“$title-$author-$publisher\n”;
}?>
book.xml

<books>
  <book>
  <author>Jack Herrington</author>
  <title>PHP Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  </books>

杰克·赫林顿
PHP黑客
奥雷利
杰克·赫林顿
播客黑客
奥雷利

在PHP中,解析文件的方式如下:

index.php

<?php
$doc = new DOMDocument();
  $doc->load( 'book.xml' );

  $books = $doc->getElementsByTagName( "book" );
  foreach( $books as $book )
  {
  $authors = $book->getElementsByTagName( "author" );
  $author = $authors->item(0)->nodeValue;

  $publishers = $book->getElementsByTagName( "publisher" );
  $publisher = $publishers->item(0)->nodeValue;

  $titles = $book->getElementsByTagName( "title" );
  $title = $titles->item(0)->nodeValue;

  echo "$title - $author - $publisher\n";
  }?>
getElementsByTagName(“book”);
foreach($books作为$book)
{
$authors=$book->getElementsByTagName(“作者”);
$author=$authors->item(0)->nodeValue;
$publisher=$book->getElementsByTagName(“publisher”);
$publisher=$publisher->item(0)->nodeValue;
$titles=$book->getElementsByTagName(“title”);
$title=$titles->item(0)->nodeValue;
回显“$title-$author-$publisher\n”;
}?>
book.xml

<books>
  <book>
  <author>Jack Herrington</author>
  <title>PHP Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  <book>
  <author>Jack Herrington</author>
  <title>Podcasting Hacks</title>
  <publisher>O'Reilly</publisher>
  </book>
  </books>

杰克·赫林顿
PHP黑客
奥雷利
杰克·赫林顿
播客黑客
奥雷利

在php中,您可以随机选择如下内容

<?php

$xml_string = 
'<gallery>
<photo id="p0001">
<title>t1</title>
<path>photos/Pergola.jpg</path>
</photo>
<photo id="p0002">
<title>t2</title>
<path>photos/Pergola.jpg</path>
</photo>
<photo id="p0003">
<title>t3</title>
<path>photos/Pergola.jpg</path>
</photo>
</gallery>';

$xml  = simplexml_load_string($xml_string);
$arr = (array) $xml;
shuffle($arr['photo']);
for($i =0; $i < 2; $i++){
  $picture = array_pop($arr['photo']);
  print_r($picture);
}

在php中,您可以随机选择如下内容

<?php

$xml_string = 
'<gallery>
<photo id="p0001">
<title>t1</title>
<path>photos/Pergola.jpg</path>
</photo>
<photo id="p0002">
<title>t2</title>
<path>photos/Pergola.jpg</path>
</photo>
<photo id="p0003">
<title>t3</title>
<path>photos/Pergola.jpg</path>
</photo>
</gallery>';

$xml  = simplexml_load_string($xml_string);
$arr = (array) $xml;
shuffle($arr['photo']);
for($i =0; $i < 2; $i++){
  $picture = array_pop($arr['photo']);
  print_r($picture);
}

首先要做的事情。尽量不要使用
文档。编写
,因为这种方法在DOM准备就绪和仍在初始化时的行为不稳定。这被认为是一种不好的做法

我还建议使用函数分解代码的复杂性,使其更具可读性

您应该知道XHR对象不是同步的。您需要等待通过
readystatechange
事件检索xml数据

最后,您不必在浏览器中构建html字符串。DOM API允许您创建锚定标记和图像标记作为可以附加到DOM树的适当节点

希望有帮助

(function() {

    //fetch the gallery photos
    getXML('include/photoLibrary.xml', function(xml) {
        var photos, pI, photo, anchor, image, anchors = [];

        //pick four photos at random
        photos = getRandom(makeArray(xml.getElementsByTagName('photo')), 4);

        //build out each photo thumb
        for(pI = 0; pI < photos.length; pI += 1) {
            photo = photos[pI];

            //create the anchor
            anchor = document.createElement('a');
            anchor.setAttribute('href', photo.getElementsByTagName('path')[0].childNodes[0].nodeValue);
            anchor.setAttribute('class', 'lytebox');
            anchor.setAttribute('data-lyte-options', 'group:vacation');
            anchor.setAttribute('data-title', photo.getElementsByTagName('description')[0].childNodes[0].nodeValue);

            //create the image
            image = document.createElement('img');
            image.setAttribute('src', photo.getElementsByTagName('thumb')[0].childNodes[0].nodeValue);
            image.setAttribute('alt', photo.getElementsByTagName('title')[0].childNodes[0].nodeValue);

            //insert the image into the anchor
            anchor.appendChild(image);

            //insert the anchor into the body (change this to place the anchors else were)
            anchors.push(anchor);
        }

        //when the DOM is loaded insert each photo thumb
        bind(window, 'load', function() {
            var aI;

            for(aI = 0; aI < anchors.length; aI += 1) {
                //replace document.body with whatever container you wish to use
                document.body.appendChild(anchors[aI]);
            }
        });
    });

    /**
     * Fetches an xml document via HTTP method GET. Fires a callback when the xml data
     * Arrives.
     */
    function getXML(url, callback) {
        var xhr;

        if(window.XMLHttpRequest) {
            xhr = new XMLHttpRequest();
        } else if(window.ActiveXObject) {
            xhr = new ActiveXObject("Microsoft.XMLHTTP");
        } else {
            throw new Error('Browser does not support XML HTTP Requests.');
        }

        //attach the ready state hander and send the request
        xhr.onreadystatechange = readyStateHandler;
        xhr.open("GET","photos.xml",false);
        xhr.send();

        function readyStateHandler() {

            //exit on all states except for 4 (complete)
            if(xhr.readyState !== 4) { return; }

            //fire the callback passing the response xml data
            callback(xhr.responseXML);
        }
    }

    /**
     * Takes array likes (node lists and arguments objects) and converts them
     * into proper arrays.
     */
    function makeArray(arrayLike) {
        return Array.prototype.slice.apply(arrayLike);
    }

    /**
     * Extracts a given number of items from an array at random.
     * Does not modify the orignal array.
     */
    function getRandom(array, count) {
        var index, randoms = [];

        //clone the original array to prevent side effects
        array = [].concat(array);

        //pull random items until the count is satisfied
        while(randoms.length < count) {
            index = Math.round(Math.random() * (array.length - 1));
            randoms.push(array.splice(index, 1)[0]);
        }

        return randoms;
    }

    function bind(element, eventName, callback) {
        if(typeof element.addEventListener === 'function') {
            return element.addEventListener(eventName, callback, false);
        } else if(typeof element.attachEvent === 'function') {
            return element.attachEvent('on' + eventName, callback);
        }
    }
})();
(函数(){
//取画廊照片
getXML('include/photoLibrary.xml',函数(xml){
var照片、pI、照片、锚定、图像、锚定=[];
//随机挑选四张照片
photos=getRandom(makeArray(xml.getElementsByTagName('photo')),4);
//建立每个照片拇指
对于(pI=0;pI