Page 1 of 1

[Solved] Read within a certain area of a file

Posted: Mon Apr 18, 2011 7:41 am
by zyntrax
Hi i have a code to read from a file, that file is a html file.
But i would only like to read within the body tags, how do i do that?
If someone could give me an example i could work from, that would be awsome.

Thanks

Code: Select all

<?php
    include 'index.php';
	
    $file = "$_GET['item']";
    $fp = fopen($file, "r");
    while(!feof($fp)) {
    ?$data = fgets($fp, 1024);
    echo "$data <br>";
    }
    fclose($fp);

?>

Re: Read within a certain area of a file

Posted: Mon Apr 18, 2011 10:46 am
by AbraCadaver

Code: Select all

// you need to do some checks on $_GET['file'] to make sure it is safe!
preg_match('#<body[^>]*>(.*?)</body>#is', file_get_contents($file), $matches);
echo $matches[1]
;

Re: Read within a certain area of a file

Posted: Tue Apr 19, 2011 8:53 am
by zyntrax
It worked perfectly, thank you.

Code: Select all

<?php
include 'index.php';
$file = "$_GET['item']";
$fp = fopen($file, "r");
while(!feof($fp)) 
{
	?$data = fgets($fp, 1024);
	if (preg_match('%<body[^>]*>(.*)</body>%is', file_get_contents($data), $matches)) 
	{
		$body = $matches[1];
	}
	else 
	{
		$body = "";
	}
}
fclose($fp);
?>