2013-04-05 41 views
-1

我想寫一個隨機生成xml文件的php。 PHP會生成一個介於1-10之間的隨機數字,每個數字1-10將在PHP中分配給它的xml文件,這將在生成相應數字時出現。使用rand()php函數來顯示隨機xml文件

到目前爲止,我有:

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

如何將XML文件集成到這個PHP?使用此XML例如:

例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> 

例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> 

所以XML文件上面已分配的數字1 & 2.我將如何分配數量在代碼中正確的XML以及如何能夠生成數字1-10的隨機XML返回,這些數字還顯示XML文件的詳細信息。

任何幫助將不勝感激!很抱歉,如果這個問題是顯而易見的,我在這一個菜鳥:)

+0

是XML的文件名爲'1.xml','2.xml' ......等等? – 2013-04-05 09:15:16

+0

RE Marty McVry: XML文件分別被稱爲dogs.xml和cats.xml。 – therunningman 2013-04-05 09:22:52

+0

RE馬克貝克: 您提到的問題討論生成XML文件保存到一個單獨的文件,而不是在PHP中。 – therunningman 2013-04-05 09:23:59

回答

0

試試這個:

<? 
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); 
?> 

將直接輸出的XML文件的XML文件的一個!
使用標題時不要輸出其他內容!

+0

謝謝!我會在下面粘貼XML文件細節嗎? – therunningman 2013-04-05 09:22:18

+0

你對檔案細節有何意義?文件名?或內容? – 2013-04-05 09:45:26

+0

內容即我上面粘貼的內容 – therunningman 2013-04-05 09:58:56

0

couldnt你只是把XML文件放入一個數組。然後在頁面提交有這樣的事情

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

我認爲這將工作。希望這可以幫助。

+0

謝謝!我會試試 – therunningman 2013-04-05 09:30:07

0

我會這樣做,這樣你就不必在每次添加一個新的xml文件時重新編碼數組的隨機值,並且不管文件被調用什麼都不重要。

<?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; 

?> 

參考:globfile_get_contentsrandcount

+0

謝謝戴爾,你在這裏用xml做些什麼意味着什麼? 對不起,如果這是一個愚蠢的問題 – therunningman 2013-04-05 09:32:32

+0

嗯,我不知道你想用它做什麼..你可以將它郵寄給某人,或者只是輸出到瀏覽器,例如在我給出的答案中輸出到瀏覽器。 – Dale 2013-04-05 09:34:44

+0

謝謝你的幫助,這正是我想要做的。 – therunningman 2013-04-05 09:43:44