John Davidson

php - Using fopen() and fread() for a search feature for website

0 comments
Message:


So I been at this for hours and maybe someone can shed some light on me.


I have this array of files to be searched in.


$searchfiles = array(
"index"=>"Home"

);

Next I have a loop which goes through the array to search for the keyword I typed in a search form so it would be like ...


    $xsearch = $_POST['xsearch'];

Following would be the loop with comments next to the echo statements


    $snippetlength=400;

$resultcount = 1;

foreach ($searchfiles as $searchpage=>$resulttitle) {

$searchpagephp = $searchpage . ".php";
$handle = fopen($searchpagephp, 'r');
$readpage = fread($handle,filesize($searchpagephp));
echo $readpage; **//OVER HERE I GET THE ENTRIE PAGE AND SEE THE KEYWORD IM LOOKING FOR**
$strippedpage = strip_tags($readpage);
echo $strippedpage; **// OVER HERE I ONLY GET CSS STYLES**
if (stripos($strippedpage,$xsearch)) {

$howmanyoccur = substr_count(strtolower($strippedpage),strtolower($xsearch));
$searchtermlocation = stripos($strippedpage,$xsearch);
if ($searchtermlocation-($snippetlength/2)<0) { $resultstart=0; } else { $resultstart=($searchtermlocation-($snippetlength/2)); }
$displayresult = substr($strippedpage,$resultstart,$snippetlength);

echo "<li><h2>$resulttitle Page <i>(Hits: $howmanyoccur)</i><br></h2>... " . str_ireplace($xsearch, ("<span style='background-color:#ffff00; font-weight:bold;'>" . strtoupper($xsearch) . "</span>"), $displayresult) . " ...<br><a href=\"$searchpage.php\">Jump to $resulttitle Page</a><br></li><br>";

$resultcount = $resultcount+1;

}

fclose($handle);

}

if ($resultcount==1) { echo "<li><i>We're sorry, but no results were found matching your search term.</i><br></li>"; }

So what Im trying to ask is why am I only getting CSS from the index file on Strip tags function?


Shouldnt I get just plain text entirely?


INDEX FILE provided
Index file as html



My Answer:
It seems like the issue might be with the way you are reading the file using `fread()` and then stripping the tags using `strip_tags()`.

When you use `fread()` to read the contents of a file, it reads the file as a string including all HTML tags. So when you pass this string to `strip_tags()`, it will only remove the HTML tags and leave the CSS styles intact because CSS styles are usually within `