2013-04-30 87 views
-1

这是我工作的PHP代码,它从Yahoo API中提取数据。如何生成随机数并将其放入字符串

<?php 
$dom->strictErrorChecking = false; 
$doc = new DOMDocument(); 
$doc->load('http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=appid&query=cats&region=us&type=resolved&start=200&results=1'); 

$Question = $doc->getElementsByTagName("Question"); 
foreach($Question as $Question) 
{ 
$Subject = $Question->getElementsByTagName("Subject"); 
$Subject = $Subject->item(0)->nodeValue; 

$Content = $Question->getElementsByTagName("Content"); 
$Content = $Content->item(0)->nodeValue; 

$ChosenAnswer = $Question->getElementsByTagName("ChosenAnswer"); 
$ChosenAnswer = $ChosenAnswer->item(0)->nodeValue; 

echo "<p><b>$Subject\n</b><br>$Content<br><i>$ChosenAnswer</i></p>"; 
} 
?> 

我需要出现在那里我有现在的编号200的URL的末尾,我需要的是1和500所以之间的随机数时,PHP页面加载该网址在$ doc->加载有时会是开始= 245,然后下一页加载可能是开始= 365等等。所以基本上每个页面加载都是从Yahoo API获取不同的url。如何在这里添加我的代码来创建随机数字?

+1

RTLM:http://php.net/rand – 2013-04-30 16:47:55

+1

你用Google搜索“[PHP随机](https://www.google.ca/search? q = php + random&aq = f&oq = php + random&sourceid = chrome&ie = UTF-8)“还没有? – 2013-04-30 16:48:04

回答

0

你可以这样做:

$doc->load('http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=appid&query=cats&region=us&type=resolved&start=' . rand(1, 500) . '&results=1'); 

更多信息:http://php.net/manual/en/function.rand.php

0

我想你忘了阅读福比dden书名为Documentation,在这本书中,你可以找到一些神秘的技巧,使其像神奇的东西,如Random numbers between range

这招叫rand,使用该招:

$randomNumber = rand(1, 500); 
0

你可以做到这一点就像这样:

$random = mt_rand(1,500); 

$doc->load('http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=appid&query=cats&region=us&type=resolved&start=' . $random . '&results=1'); 

我用.(点)操作符来这里 “添加” 字符串。

简化版容易理解:

$x = 5; 

$some_string = 'foo' . $x . 'bar'; // will produce text: foo5bar 

echo $some_string;