jiten2015 jiten2015 - 1 year ago 52
HTML Question

Searching two internal html files simultaneously with PHP

I have a PHP code (index.php) for searching keywords in two html files (data.html & data2.html). When I search a keyword, such as "Ann", would it be possible to parse both html files and shows the line matching the keyword (i.e. This is Ann.)? The source codes are as follows:

index.php


<?php
$search = $_GET['keyword'];
$data = file('data.html');

$check = false;
foreach($data as $match)
{
if(strpos($match, $search) !== false)
{
$check = true;
$output = '<div>'.$match.'<div>';
echo $output;

}
}
?>


data.html



This is Ann.
This is Bob.
This is Candy.


data2.html



This is Ann.
This is Peter.
This is Bob.


Many thanks for help.

Answer Source

You can use like that;

<?php

$search = $_GET['keyword'];
$data = file('data.txt');
$data2 = file('data2.txt');

$datas = Array($data, $data2);
foreach($datas as $index => $data){
    foreach($data as $lineNumber => $match )
    {
      if(strpos($match, $search) !== false)
      {
        echo "<div><b>$index 'th file</b>. Line number: $lineNumber . Match: $match <br />";
      }
    }
}
?>

If you need read more than one file at the same time you just add like data3 and add also array too.