php 文件中随机取出一条数据

  1. <?php
  2. //第一种方法:
  3. $line = getrandline1('test.txt');
  4. function getrandline1($filename)
  5. {
  6. $linenum = 0;
  7. $fh = fopen($filename, 'r');
  8. while(!feof($fh))
  9. {
  10. if($rowcontents = fgets($fh))
  11. {
  12. $linenum++;
  13. $contens[] = $rowcontents;
  14. }
  15. }
  16. $randline = mt_rand(0, $linenum - 1);
  17. $line = $contens[$randline];
  18. fclose($fh);
  19. return $line;
  20. }
  21. //第二种方法:
  22. $line = getrandline2('test.txt');
  23. function getrandline2($filename)
  24. {
  25. $contents = file('test.txt');
  26. $linenum = count($contents);
  27. $randline = mt_rand(0, $linenum - 1);
  28. $line = $contents[$randline];
  29. return $line;
  30. }
  31. //第三种方法:
  32. $line = getrandline3('test.txt');
  33. function getrandline3($filename)
  34. {
  35. $contents = file('test.txt');
  36. shuffle($contents);
  37. return $contents[0];
  38. }
  39. //第四种方法:
  40. $line = getrandline4('test.txt');
  41. function getrandline4($filename)
  42. {
  43. $linenum = 0;
  44. $fh = fopen($filename, 'r');
  45. while(!feof($fh))
  46. {
  47. if($linecontents = fgets($fh))
  48. {
  49. $linenum++;
  50. $randint = (mt_rand(1, 1000000 * $linenum) - 1)/1000000);
  51. if($randint < 1)
  52. {
  53. $line = $linecontents;
  54. }
  55. }
  56. }
  57. fclose($fh);
  58. return $line;
  59. }
  60. ?>