如何告诉PHP在到达行尾时停止而不返回错误?

如何告诉PHP在到达行尾时停止而不返回错误?

问题描述:

I am trying to read the content of a text-file, but have no idea how to tell PHP to break when it has reached the end.

The current code is:

<?php

$file = "campaign1_20_db.txt";
$content = file_get_contents($file);
$string = explode("
",$content);

$index = 0;

while ($index <= 100):

$index = $index + 1;
endwhile;

?>

How do i replace the 100 with something that depends on PHP reaching the end of the textfile?

我正在尝试阅读文本文件的内容,但不知道如何告诉PHP中断 它已经到了最后。 p>

当前代码是: p>

 &lt;?php 
 
 $ file =“campaign1_20_db。  txt“; 
 $ content = file_get_contents($ file); 
 $ string = explode(”
“,$ content); 
 
 $ index = 0; 
 
while($ index&lt; = 100  ):
 
 $ index = $ index + 1; 
endwhile; 
 
?&gt; 
  code>  pre> 
 
 

如何将100替换为100 取决于PHP到达文本文件的末尾? p> div>

Since you're using explode, you'll have an array of lines. However, you could simply have:

$strings = file($file);

which does the exact same thing for you without the explict explode. You can then simply do a foreach loop on that array:

foreach($strings as $line) {
  ...
}

to loop over each of those lines. However, it appears you're just trying to count how many lines there are, so the foreach isn't even necessary:

$total_lines = count($strings);

(I hope you have there something more complex than counting lines one by one, otherwsie disregard this answer)

You may use lighter (in terms of consumed memory) algorithm to iterate through files' lines:

$f = fopen('campaign1_20_db.txt');
while ($line = fgets($f)) {
    // your code
}

If you want to see if you have reached the end of the file, then you have to use the good old way of fopen, fread and feof. Code would be something like

 <?php
$file = fopen("file.txt");
while(!feof($file))  {
$content .= fread( $file, 1024 );
}

Feof

The function you are looking at is called file end of. This basically tells that you have reached at the end of the file or not.

Fread

In the fread command, you are passing the file handler (returned by fopen) and the amount of bytes that have to be read. The maximum value depends on your PHP settings.