Is it possible to read a section of a file with PHP

Hi,

Let’s say I have a PHP file (index.php) that displays another PHP file (info.php) within a textarea using file_get_contents() function. Is it possible to define some sort of tags in info.php so that index.php will only get the content between those tags?

For example, let’s say info.php is like the following:

<?php
// Some PHP code here...
[DISPLAY]
Content I want to display...
[/DISPLAY]
// Some PHP code here...
?>

Is there a way to get only the content between display tags or something like that?

Hi,

AFAIK the function file_get_contents() loads all the contents of a file into a string.
If you know the exact position of the content you want, you can use the offset and maxlength parameters to read only a section.
For example:

<?php
// Read 14 characters starting from the 21st character
$section = file_get_contents('./yourFile.php', NULL, NULL, 20, 14);
var_dump($section);
?>

Or, if it’s not too much of a performance hit, maybe you could get the whole file as a string, then simply remove everything before and after the markers using substr().

yup you can use file_get_contents which returns values as string then use regular expression to extract the part identifying the pattern…

I will use that on different files so there is no exact position. I will try and see what I can do with subsrt().

Your suggestion seems to be the solution, could you please elaborate it a little, maybe a very simple example?

ok using this approach,if the content of the page you are accessing is dynamic(which is most of the time)
$section = file_get_contents(‘./yourFile.php’, NULL, NULL, 20, 14);
will return different part every time the page is changed.

file_get_contents will return the html source(from top header,meta to /html) code of the page(file) you access in string format.

The content may be different but structure of the file may be same

for eg,if you want to get values between

<table><tr><td>value–can be anything</td>
or
<table class=‘name’>…

so you can use those kind of information to write an regular expression and get the value which will be much generic…
I mean run regular expression over string obtained from file_get_contents and get the value you want.

Somethinglike this, maybe:

<?php
$string = "some uninteresting stuff [DISPLAY]the real content[/DISPLAY] some more uninteresting stuff";
$pattern = '/\\[DISPLAY\\](.*)\\[\\/DISPLAY\\]/';
$result = preg_match ($pattern, $string, $matches );
echo "<p>Result = $matches[1]</p>";
?>