[Solved] Read within a certain area of a file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
zyntrax
Forum Commoner
Posts: 32
Joined: Wed Apr 13, 2011 2:23 am
Location: Sweden

[Solved] Read within a certain area of a file

Post 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);

?>
Last edited by zyntrax on Tue Apr 19, 2011 8:56 am, edited 1 time in total.
User avatar
AbraCadaver
DevNet Master
Posts: 2572
Joined: Mon Feb 24, 2003 10:12 am
Location: The Republic of Texas
Contact:

Re: Read within a certain area of a file

Post 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]
;
mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
zyntrax
Forum Commoner
Posts: 32
Joined: Wed Apr 13, 2011 2:23 am
Location: Sweden

Re: Read within a certain area of a file

Post 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);
?>
Post Reply