Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

The loop never stop, also it always print, not only when $i is equal 8

$file  = file_get_contents ($fileUrl);
$i = 0;
        
while ($line = explode ("
", $file)) {
            
    if ($i == 8) {
        print_r ($line);
        exit ();
    }
            
    $i++;
}

By the way, I need to use file_get_contents because I am using DOM, but I use that code because I need the data in line number 8, is there any better way to get a specific line


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

It is infinite because explode always explodes the entire file string and it never fails. You can read it into an array, but this is only useful without the exit if you are doing things with other lines in the file:

foreach(file($fileUrl) as $line) {
    if ($i == 8) {  // actually the ninth line
        print_r ($line);
    }                
    $i++;
}

Or read it as you are and get the proper line:

$lines = explode("
", $file);
print_r($lines[8]);  // actually the ninth line

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...