最模板 - 外贸网站建设,外贸网站模板

最模板

当前位置: 首页 > 建站教程 > php教程 >

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

时间:2014-06-09 16:40来源: 作者: 点击: 次
?php //第一种方法: $line =getrandline1( test.txt ); function getrandline1( $filename ) { $linenum =0; $fh = fopen ( $filename , r ); while (! feof ( $fh )) { if ( $rowcontents = fgets ( $fh )) { $linenum ++; $contens []= $rowcontents ; } } $ra
  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. //第二种方法: 
  23. $line = getrandline2('test.txt'); 
  24. function getrandline2($filename) 
  25. { 
  26.  $contents = file('test.txt'); 
  27.  $linenum = count($contents); 
  28.  $randline = mt_rand(0, $linenum - 1); 
  29.  $line = $contents[$randline]; 
  30.  return $line; 
  31. } 
  32.   
  33. //第三种方法: 
  34. $line = getrandline3('test.txt'); 
  35. function getrandline3($filename) 
  36. { 
  37.  $contents = file('test.txt'); 
  38.  shuffle($contents); 
  39.  return $contents[0]; 
  40. } 
  41.   
  42. //第四种方法: 
  43. $line = getrandline4('test.txt'); 
  44. function getrandline4($filename) 
  45. { 
  46.  $linenum = 0; 
  47.  $fh = fopen($filename, 'r'); 
  48.  while(!feof($fh)) 
  49.  { 
  50.   if($linecontents = fgets($fh)) 
  51.   { 
  52.    $linenum++; 
  53.                         $randint = (mt_rand(1, 1000000 * $linenum) - 1)/1000000); 
  54.    if($randint < 1) 
  55.    { 
  56.     $line = $linecontents; 
  57.    } 
  58.   } 
  59.  } 
  60.  fclose($fh); 
  61.  return $line; 
  62. } 
  63. ?> 
(责任编辑:admin)
------分隔线----------------------------
栏目列表
推荐内容