2017-03-18 29 views
0

我们需要一个cronjob来创建我们的匿名页面的静态版本。PHP的包装与嵌入式JavaScript和CSS的任何网址?

每个URL都应该保存为一个HTML文档,并将所有外部<script src="">标记替换为其javascript,并将所有<link href="">标记替换为其CSS。 (css不需要内联属性)。

在我重新发明轮子之前,有没有PHP中的任何简单的打包脚本来做到这一点?

回答

0

我根本解决......

$ch = curl_init(); 
    curl_setopt($ch, CURLOPT_HEADER, false); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); 
    curl_setopt($ch, CURLOPT_URL, $url); 
    curl_setopt($ch, CURLOPT_REFERER, $url); 
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); 
    //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); 
    //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); 
    curl_setopt($ch, CURLOPT_VERBOSE, 1); 
    $html = curl_exec($ch); 
    if($errno = curl_errno($ch)) { 
     $error_message = curl_strerror($errno) . ' -- ' . $url; 
     die ("cURL error ({$errno}):\n {$error_message}"); 
    } 
    curl_close($ch); 

    $doc = new DOMDocument(); 
    $doc->strictErrorChecking = false; 
    $doc->recover = true; 
    $internalErrors = libxml_use_internal_errors(true); 
    $doc->loadHTML($html); 
    libxml_use_internal_errors($internalErrors); 

    foreach($doc->getElementsByTagName('script') as $script) { 
     if($script->hasAttribute('src')) { 
      $path = $script->getAttribute('src'); 
      if (strpos($path, 'http') !== 0) { 
      if (strpos($path, '?') > -1) $path = substr($path, 0, strpos($path, '?')); 
      $path = ROOT_CD . $path; 
      } 
      $source = file_get_contents($path); 

      $new = $doc->createElement('script'); 
      $new->setAttribute('type', 'text/javascript'); 
      $new->setAttribute('sourcePath', $script->getAttribute('src')); 
      $new->setAttribute('language', 'javascript'); 
      $source = $doc->createTextNode($source); 
      $new->appendChild($source); 

      $script->parentNode->replaceChild($new, $script); 
     } 
    } 

    foreach($doc->getElementsByTagName('link') as $script) { 
     if($script->hasAttribute('href') && $script->hasAttribute('rel')) { 
      $type = $script->getAttribute('rel'); 
      if ($type !== 'stylesheet') continue; 

      $path = $script->getAttribute('href'); 
      if (strpos($path, 'http') !== 0) { 
      if (strpos($path, '?') > -1) $path = substr($path, 0, strpos($path, '?')); 
      $path = ROOT_CD . $path; 
      } 
      $source = file_get_contents($path); 

      $new = $doc->createElement('style'); 
      $new->setAttribute('type', 'text/css'); 
      $new->setAttribute('sourcePath', $script->getAttribute('src')); 
      $source = $doc->createTextNode($source); 
      $new->appendChild($source); 

      $script->parentNode->replaceChild($new, $script); 
     } 
    } 


    $html = $doc->saveHTML(); 
    require_once '../preprocessing/minifier.php'; 
    $html = compressHTML($html); 
    file_put_contents("static-login-".$platform.".html", $html); 
    echo $html;