Reputation: 117
I would like to extract the first x lines of an html page I know that I can extract the amount of characters with something like this:
file_get_contents('http://xx.xxx.158.239/fin.html' , NULL, NULL, 0, 125);
but what about lines ? like to extract the text from line 1 to line 4? is that possible ?
Upvotes: 0
Views: 1841
Reputation: 9608
Here's a little code snippet that you might find useful:
$file = 'http://xx.xxx.158.239/fin.html'; // remote or local file
$lines = 3; // how many lines do you want?
if (file_exists($file)) {
$contents = @file_get_contents($file); // suppress errors, esp. for remote files
$head = implode("\n", array_slice(explode("\n", $contents), 0, $lines));
} else {
$head = 'File does not exist';
}
echo $head;
Upvotes: 2
Reputation: 819
You can use file on a File- or URL-Handle created by fopen to load the content into an array and read only the relevant lines.
To get the content line by line in a loop, you can use fgets.
Upvotes: 0
Reputation: 2098
You can read the file using dedicated method calls instead of the one-for-all file_get_contents()
:
$fp = fopen('my/file/name', 'r');
for ($i = 0; $i < 4; $i++) {
if (feof($fp)) {
echo 'EOF reached';
break;
}
echo fgets($fp);
}
fclose($fp);
Upvotes: 3