【问题标题】:Adding parameters to URLs from HTML file从 HTML 文件向 URL 添加参数
【发布时间】:2016-08-16 14:51:23
【问题描述】:

我正在创建一个本地 php 脚本来操作从 Photoshop 导出的 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)));
}

从 photoshop 导出的 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。

【问题讨论】:

  • 这不会引发错误 - 那么请不要suppress错误,这可能会有所帮助。
  • 每次迭代都写入和重新加载文件?????

标签: php html url preg-replace file-put-contents


【解决方案1】:

我看到你的 html 文件中有相同的 url, 最好将它们保存在原位,而不是使用preg_replace。你可以用这个:

$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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-06
    • 2019-02-24
    • 2011-03-07
    • 2022-12-28
    • 1970-01-01
    • 2018-04-28
    • 2021-11-11
    • 2019-07-04
    相关资源
    最近更新 更多