Reducing execution time of an HTML parsing script The script is intended to return an array with texts containing specific words in English and the equivalent texts in Polish from EUR-Lex - a website with EU documents.

The script downloads the page which address is specified by the passed variable. Then this page is parsed using regular expressions for the document codes. This code are then used to access another page. This page is then parsed for elements contained within &lt;tr&gt; tags, which, if their content contains words from the variable (checked with a regular expression), are saved in an array.

For variables containing 1-2 words the script works fairly well; not so well for more. I got complaints from my free hosting provider (hostinger.in) that the script uses too much resources. I have other scripts run before that script, but not simultaneously, so I don't if they contribute to the problem.

&lt;?php
//test variables
//$var1 = 'board_of_directors';
//$var1 = 'affidavit';
$var1 = 'event_of_default';
$var1 = explode("_", $var1);
$words = implode(" ",$var1);
if (count($var1) &gt;= 2) {
    $var1 = implode("%20",$var1);
} else {
    $var1 = implode("%",$var1);
}
$var1 = "\""."$var1"."\"";
$html = file_get_contents("http://eur-lex.europa.eu/search.html?qid=1&amp;text=$var1&amp;scope=EURLEX&amp;type=quick&amp;lang=en");
preg_match_all('/CELEX:(\w+)&amp;/si', $html, $matches2);
$result = array_unique($matches2[1]);
$result2 = file_get_contents("http://eur-lex.europa.eu/legal-content/EN-PL/TXT/?uri=CELEX:$result[0]&amp;from=EN");
$dom = new domDocument; 
libxml_use_internal_errors(true);
$dom-&gt;loadHTML($result2); 
$items = $dom-&gt;getElementsByTagName('tr');
$return_array = array();

for ($i = 0; $i &lt; $items-&gt;length - 1; $i++) {
    $text1 = $items-&gt;item($i)-&gt;childNodes-&gt;item(0)-&gt;textContent;
    if (preg_match('/' . $words . '/i', $text1)) {
        $text2 = $items-&gt;item($i)-&gt;childNodes-&gt;item(1)-&gt;textContent;
        array_push($return_array, $text1);
        array_push($return_array, $text2);
    }
}
echo json_encode($return_array);

?&gt;
There's a few things you can do to improve here:


Use curl instead of get_file_contents, it speeds the document retrieval up so much.
The following could be converted to a ternary statement:



if (count($var1) &gt;= 2) {
    $var1 = implode("%20",$var1);
} else {
    $var1 = implode("%",$var1);
}



Notice that the condition is reversed:

$var1 = implode('%' + (!count($var1) &gt;= 2 ?: "20"), $var1);



You shouldn't be joining strings like this: "\""."$var1"."\"":


Do this instead: "\"{$var1}\"" (see that the variable is wrapped in curly braces)


Don't array_push, use the $array[] notation instead.

$return_array[] = $text1;
$return_array[] = $text2;