Aggregating HTML files
Basically you need to remove the unused fopen() call and change ponderous operators to handy ones as for some reason you made a peculiar choice in favor of the former, like for vs. foreach, array_push vs simple assignment, etc. Also consider a cleaner way to output HTML 

&lt;?php
$pattern = "domain/folder/*.*";
$files = glob($pattern);

// loop over all the files, saving their contents and ids to arrays

$contents = [];
$titles = [];
$ids = [];
foreach ($files as $filename)
{
    $data = file_get_contents($filename);
    $contents[] = $data;

    preg_match('#&lt;title&gt;(.*?)&lt;\/title&gt;#', $data, $match);
    $titles[] = $match[1];

    $ids[] = preg_split('#( |-|,)#', $match[1])[0];
}
?&gt;
&lt;div id='navigation'&gt;
&lt;ul&gt;
&lt;?php foreach ($titles as $x =&gt; $title): ?&gt;
    &lt;li&gt;&lt;a href="#&lt;?=$ids[$x]?&gt;"&gt;&lt;?=$title?&gt;&lt;/a&gt;&lt;/li&gt;
&lt;?php endforeach ?&gt;
&lt;/ul&gt;
&lt;/div&gt;

&lt;div id='content'&gt;
&lt;?foreach ($contents as $x =&gt; $content): ?&gt;
    &lt;div id="&lt;?=$ids[$x]?&gt;"&gt;&lt;?=$content?&gt;&lt;/div&gt;
&lt;?php endforeach ?&gt;
&lt;/div&gt;