Using the rand () php function to display random x

2019-09-20 20:16发布

问题:

This question already has an answer here:

  • How would I use php to generate random XML files? 1 answer

I am trying to write a php that generates xml files randomly. The php would generate a random number between 1-10 inclusive and each number 1-10 would have a xml file assigned to it in the php which would appear when the respective number is generated.

So far I have:

<?php
 print rand() . "<br>"; 
 print rand(1, 10); 
 ?>

How do I integrate the xml files into this php? Using this xml example:

Example 1

<?xml version="3.0" encoding="utf-8" ?> 
<channel>
<title>The Dog in the Park</title> 
<link>http://pets.com/doginthepark/</link> 
<description>
  The dog in the park
<item> 
<guid>1234</guid>
<title>poodle's video</title>

Example 2

<?xml version="3.0" encoding="utf-8" ?> 
<channel>
<title>The Cat in the Park</title> 
<link>http://pets.com/kitteninthepark/</link> 
<description>
  The cat in the park
<item> 
<guid>1235</guid>
<title>kitten video</title>
<item>
<guid>123455</guid>
<title>tiger video</title>

So the XML files above have the assigned numbers 1 & 2. How would I assign the number in code to the correct XML and how would I be able to generate a random XML return of the numbers 1-10 which also display the XML file details.

Any help will be greatly appreciated! Sorry if this question is obvious, I'm a rookie at this :)

回答1:

couldnt you just put the xml files into an array. then on submit of the page have something like this

   echo file_get_contents($xmlarray[rand(1,10)]);

I presume this would work. hope this helps.



回答2:

I would do it this way so that you don't have to recode the array random values every time you add a new xml file, and it wont matter what the files are called.

<?php

    $files = glob('path/to/files/*.xml');
    $xml = file_get_contents($files[rand(0, count($files)-1)]);
    // do something with the xml here
    echo $xml;

?>

For reference: glob, file_get_contents, rand, count



回答3:

Try this:

<?
header('Content-type: text/xml');
$XMLFiles = array ("path/dogs.xml", "path/cats.xml", "path/moreFiles.xml");
$XMLFile = $XMLFiles[rand(0,9)];
header('Content-Disposition: attachment; filename="'.$XMLFile.'"');
print file_get_contents($XMLFile);
?>

Will directly output your one of your XML files as a XML file!
Dont output anything else when using headers!



标签: php xml random