<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>运达&#039;s  blog &#187; fseek</title>
	<atom:link href="https://www.yunda51.com/?feed=rss2&#038;tag=fseek" rel="self" type="application/rss+xml" />
	<link>https://www.yunda51.com</link>
	<description>运达的博客</description>
	<lastBuildDate>Wed, 12 Nov 2025 07:58:26 +0000</lastBuildDate>
	<language>zh-CN</language>
		<sy:updatePeriod>hourly</sy:updatePeriod>
		<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.0.19</generator>
	<item>
		<title>PHP对大文件的处理思路</title>
		<link>https://www.yunda51.com/?p=1649</link>
		<comments>https://www.yunda51.com/?p=1649#comments</comments>
		<pubDate>Sat, 31 Oct 2015 08:46:05 +0000</pubDate>
		<dc:creator><![CDATA[运达]]></dc:creator>
				<category><![CDATA[php技术]]></category>
		<category><![CDATA[fseek]]></category>
		<category><![CDATA[大文件]]></category>

		<guid isPermaLink="false">http://www.yunda51.com/?p=1649</guid>
		<description><![CDATA[需求： 现有一个1G左右的日志文件，大约有500多万行， 用php返回最后几行的内容。 在php中，对于文件的<a href="https://www.yunda51.com/?p=1649" class="read-more">Continue Reading</a>]]></description>
				<content:encoded><![CDATA[<p>需求： 现有一个1G左右的日志文件，大约有500多万行， 用php返回最后几行的内容。</p>
<p>在php中，对于文件的读取时，最快捷的方式莫过于使用一些诸如file、file_get_contents之类的函数，简简单单的几行代码就能很漂亮的完成我们所需要的功能。但当所操作的文件是一个比较大的文件时，这些函数可能就显的力不从心, 下面将从一个需求入手来说明对于读取大文件时，常用的操作方法。<br />
<strong>1. 直接采用file函数来操作</strong></p>
<p>由于 file函数是一次性将所有内容读入内存，而php为了防止一些写的比较糟糕的程序占用太多的内存而导致系统内存不足，使服务器出现宕机，所以默认情况下限制只能最大使用内存16M,这是通过php.ini里的memory_limit = 16M来进行设置，这个值如果设置-1，则内存使用量不受限制。</p>
<p>下面是一段用file来取出这具文件最后一行的代码。代码执行大概2分钟左右。</p>
<pre class="wp-code-highlight prettyprint">
$fp = fopen($file, &quot;r&quot;);
	$num = 10;
	$chunk = 4096;
	$fs = sprintf(&quot;%u&quot;, filesize($file));
	$max = (intval($fs) == PHP_INT_MAX) ? PHP_INT_MAX : filesize($file);
	for ($len = 0; $len &lt; $max; $len += $chunk) {
	  $seekSize = ($max - $len &gt; $chunk) ? $chunk : $max - $len;
	    fseek($fp, ($len + $seekSize) * -1, SEEK_END);
	    $readData = fread($fp, $seekSize) . $readData;
	    if (substr_count($readData, &quot;\n&quot;) &gt;= $num + 1) {
	        preg_match(&quot;!(.*?\n){&quot;.($num).&quot;}$!&quot;, $readData, $match);
	        $data = $match[0];
	        break;
	    }
	}
	fclose($fp);
	echo $data;
</pre>
<p>我机器是2个G的内存，当按下F5运行时，系统直接变灰，差不多20分钟后才恢复过来，可见将这么大的文件全部直接读入内存，后果是多少严重，所以不在万不得以，memory_limit这东西不能调得太高，否则只有打电话给机房，让reset机器了。<br />
<strong>2.直接调用linux的tail命令来显示最后几行</strong></p>
<p>在linux命令行下,可以直接使用tail -n 10 access.log很轻易的显示日志文件最后几行,可以直接用php来调用tail命令,执行php代码如下.整个代码执行完成耗时 0.0034 (s)</p>
<pre class="wp-code-highlight prettyprint">
file = &#039;access.log&#039;;
$file = escapeshellarg($file); // 对命令行参数进行安全转义
$line = `tail -n 1 $file`;
echo $line;
</pre>
<p>3. 直接使用php的fseek来进行文件操作</p>
<p>这种方式是最为普遍的方式,它不需要将文件的内容全部读入内存,而是直接通过指针来操作,所以效率是相当高效的.在使用fseek来对文件进行操作时,也有多种不同的方法,效率可能也是略有差别的,下面是常用的两种方法.</p>
<p>方法一：</p>
<p>首先通过fseek找到文件的最后一位EOF，然后找最后一行的起始位置，取这一行的数据，再找次一行的起始位置，再取这一行的位置，依次类推，直到找到了$num行。</p>
<pre class="wp-code-highlight prettyprint">
	function tail($fp,$n,$base=5)
	{
	    assert($n&gt;0);
	    $pos = $n+1;
	    $lines = array();
	    while(count($lines)&lt; =$n){
	        try{
	            fseek($fp,-$pos,SEEK_END);
	        } catch (Exception $e){
	            fseek(0);
	            break;
	        }
	        $pos *= $base;
	        while(!feof($fp)){
	            array_unshift($lines,fgets($fp));
	        }
	    }
	    return array_slice($lines,0,$n);
	}
	var_dump(tail(fopen(&quot;access.log&quot;,&quot;r+&quot;),10));

</pre>
<p>方法二:</p>
<p>还是采用fseek的方式从文件最后开始读,但这时不是一位一位的读,而是一块一块的读,每读一块数据时,就将读取后的数据放在一个buf里,然后通过换行符(\n)的个数来判断是否已经读完最后$num行数据.</p>
<pre class="wp-code-highlight prettyprint">
$fp = fopen($file, &quot;r&quot;);
	$line = 10;
	$pos = -2;
	$t = &quot; &quot;;
	$data = &quot;&quot;;
	while ($line &gt; 0) {
	    while ($t != &quot;\n&quot;) {
	        fseek($fp, $pos, SEEK_END);
	        $t = fgetc($fp);
	        $pos --;
	    }
	    $t = &quot; &quot;;
	    $data .= fgets($fp);
	    $line --;
	}
	fclose ($fp);
	echo $data
</pre>
<p>方法三:</p>
<pre class="wp-code-highlight prettyprint">
ini_set(&#039;memory_limit&#039;,&#039;-1&#039;);
$file = &#039;access.log&#039;;
$data = file($file);
$line = $data[count($data)-1];
echo $line;
</pre>
<p>转自<a herf="http://www.nowamagic.net/librarys/veda/detail/1995">Veda原型博客！</a></p>
]]></content:encoded>
			<wfw:commentRss>https://www.yunda51.com/?feed=rss2&#038;p=1649</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
