这是我的工作PHP代码,从雅虎API获取数据。
<?php
$dom->strictErrorChecking = false;
$doc = new DOMDocument();
$doc->load( 'http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=appid&query=cats®ion=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>";
}
?>
我需要做的是在url的末尾,我现在有了数字200,我需要它是1到500之间的随机数。所以当php页面加载时,$doc->load中的url有时会是start=245然后下一个页面加载可能是start=365等等。基本上每个页面加载都会从雅虎API获取不同的url。我如何添加到我的代码来创建随机数?
检查rand()
,我想它会起作用的:
rand(min,max):
http://www.php.net/manual/en/function.rand.php 你可以这样做:
$doc->load( 'http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=appid&query=cats®ion=us&type=resolved&start=' . rand(1, 500) . '&results=1' );
更多信息:http://php.net/manual/en/function.rand.php
我想你忘记读这本叫做Documentation
的禁书了,在这本书里你可以找到一些神秘的技巧来制造神奇的东西,比如Random numbers between range
。
这个技巧叫做rand
,使用这个技巧:
$randomNumber = rand(1, 500);
你可以这样做:
$random = mt_rand(1,500);
$doc->load( 'http://answers.yahooapis.com/AnswersService/V1/questionSearch?appid=appid&query=cats®ion=us&type=resolved&start=' . $random . '&results=1' );
我使用.
(点)操作数来"添加"字符串。
简化版:
$x = 5;
$some_string = 'foo' . $x . 'bar'; // will produce text: foo5bar
echo $some_string;