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

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

dom - what is wrong with this code, I am using PHP 8

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...