Bonjour,

Le code PHP ci-dessous permet de parser puis d’afficher et paginé le contenu d’un fichier texte contenant plus de 830 000 lignes.

Le problème est qu’il utilise plus de mémoire qu’il n'ait allouée à PHP, c’est-à-dire 128mo.

Avez-vous des recommandations sur l’optimisation du code PHP pour baisser la consommation de mémoire lors de son exécution ?

Merci de votre aide.

Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?php
$lines = file_get_contents('file.txt');
 
$perpage = 5; //Number of lines per page
 
$searchString = $_GET['search']; //Insert word(s) you're searching for
$pattern = preg_quote($searchString, '/');
$pattern = "/^.*$pattern.*/mi";
 
if(preg_match_all($pattern, $lines, $matches)){
    $line_amount = count($matches[0]);
} else {
    echo "No matches found";
}
 
$p = isset($_GET['page']) ? $_GET['page'] : 1;
for ($i = (($p * $perpage) - $perpage); $i <= (($perpage * $p) - 1); $i++){
    if($i >= $line_amount){
        break;
    } else {
        echo $matches[0][$i].'<br />';
    }
}
?>
 
<table summary="" cellpadding="10" cellspacing="0"  border="0">
    <tr>
	<?php
	$link = "";
	$page = $_GET['page']; // your current page
	$pages=$line_amount/$perpage; // Total number of pages
 
	$perpage=5  ; // May be what you are looking for
 
    if ($pages >=1 && $page <= $pages)
    {
        $counter = 1;
        $link = "";
        if ($page > ($perpage/2))
			$link .= "<td><a href=\"?page=1\">1 </a></td> <td>...</td> ";
 
        for ($x=$page; $x<=$pages;$x++)
        {
            if($counter < $perpage)
                $link .= "<td><a href=\"?page=" .$x."\">".$x." </a></td>";
 
            $counter++;
        }
        if ($page < $pages - ($perpage/2))
				$link .= "<td>...</td> " . "<td><a href=\"?page=" .$pages."\">".$pages." </a></td>";
    }
 
    echo $link;
	?>
	</tr>
</table>