2016-08-16 4 views
0

PhotoshopからエクスポートされたHTMLファイルを操作するローカルPHPスクリプトを作成しています。私はすべてのURLにいくつかのパラメータを追加する必要があります。これは私が試したものです:フォトショップからエクスポートHTMLファイルからURLにパラメータを追加する

$newHtmlFile = 'exported.html'; //HTML file exported from photoshop 
$htmlContent = file_get_contents($newHtmlFile); 

$randomQuery = 'utm_source=onlinenewsletter&utm_medium=email&utm_content=random&utm_campaign=test'; 

$dom = new DOMDocument; 
@$dom->loadHTML($htmlContent); 
foreach($dom->getElementsByTagName('a') as $thisLink){ 
    $thisUrl = $thisLink->getAttribute('href'); 
    $parsedUrl = parse_url($thisUrl); 
    if($parsedUrl['path'] == null){ $thisUrl .= '/'; } 
    $separator = ($parsedUrl['query'] == NULL) ? '?' : '&'; 
    $newUrl = $thisUrl . $separator . $query; 

    file_put_contents($newHtmlFile, preg_replace('~\b' .$thisUrl. '\b~u', $newUrl, file_get_contents($newHtmlFile))); 
} 

例HTMLを:

<html> 
<head> 
    <title>Some Page</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
</head> 
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0"> 
    <table id="Tabla_01" width="570" height="617" border="0" cellpadding="0" cellspacing="0"> 
     <tr> 
      <td> 
       <a href="http://somepage.com/es/es/"> 
        <img src="images/some_image_01.jpg" width="285" height="160" border="0" alt=""></a></td> 
      <td> 
       <a href="http://somepage.com/es/es/"> 
        <img src="some_image_02.jpg" width="285" height="160" border="0" alt=""></a></td> 
     </tr> 
    </table> 
</body> 

を。これは、エラーをスローしませんし、それはURLを置き換えるものではありません。

+0

:あなたはこれを使用することができます助けるかもしれない。 – Script47

+0

すべての繰り返しをファイルに書き込んでリロードする – cske

答えて

0

あなたのHTMLファイルに同じURLがありますので、 preg_replaceの代わりにそのURLに保存してください。その後、ない[抑止](http://php.net/manual/en/language.operators.errorcontrol.php)エラーを行わないことをしてください - これは、エラーがスローされます* *

$newHtmlFile = 'exported.html'; //HTML file exported from photoshop 
$htmlContent = file_get_contents($newHtmlFile); 

$randomQuery = 'utm_source=onlinenewsletter&utm_medium=email&utm_content=random&utm_campaign=test'; 

$dom = new DOMDocument; 

@$dom->loadHTML($htmlContent); 

foreach($dom->getElementsByTagName('a') as $thisLink){ 
    $thisUrl = $thisLink->getAttribute('href'); 
    $parsedUrl = parse_url($thisUrl); 
    if($parsedUrl['path'] == null){ $thisUrl .= '/'; echo "here";} 
    $separator = !isset($parsedUrl['query']) ? '?' : '&'; 
    $newUrl = $thisUrl . $separator . $randomQuery; 

    //echo "$thisUrl - $newUrl <br/>"; 
    //file_put_contents($newHtmlFile, preg_replace('@' .$thisUrl. '@', $newUrl, file_get_contents($newHtmlFile))); 
    $thisLink->setAttribute('href', $newUrl); 
} 

file_put_contents($newHtmlFile, $dom->saveHTML()); 
関連する問題