Last active
January 29, 2017 13:26
-
-
Save Abdelhady/9ae1081abe004714972bda835bf83559 to your computer and use it in GitHub Desktop.
Use this utility function to append GA's campaign (or any other parameters with a small modification) to all links in your email at once, in an efficient way which uses `DOMDocument::loadHTML` instead of using custom regex.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* appending campaign parameters to every single link `<a href=''></a>` | |
* in the given $bodyHtml | |
* | |
* @param type $bodyHtml | |
*/ | |
public function appendCampaignPrameters($bodyHtml, $utmCampaign) { | |
$newParams = [ | |
'utm_source' => 'email', | |
'utm_medium' => 'email', | |
'utm_campaign' => $utmCampaign | |
]; | |
$doc = new \DOMDocument(); | |
$internalErrors = libxml_use_internal_errors(true); //http://stackoverflow.com/a/10482622/905801 | |
$doc->loadHTML($bodyHtml); | |
libxml_use_internal_errors($internalErrors); | |
foreach ($doc->getElementsByTagName('a') as $link) { | |
$url = parse_url($link->getAttribute('href')); | |
$gets = $newParams; | |
if (isset($url['query'])) { | |
$query = []; | |
parse_str($url['query'], $query); | |
$gets = array_merge($query, $newParams); | |
} | |
$newHref = ''; | |
if (isset($url['scheme'])) { | |
$newHref .= $url['scheme'] . '://'; | |
} | |
if (isset($url['host'])) { | |
$newHref .= $url['host']; | |
} | |
if (isset($url['port'])) { | |
$newHref .= ':' . $url['port']; | |
} | |
if (isset($url['path'])) { | |
$newHref .= $url['path']; | |
} | |
$newHref .= '?' . http_build_query($gets); | |
if (isset($url['fragment'])) { | |
$newHref .= '#' . $url['fragment']; | |
} | |
$link->setAttribute('href', $newHref); | |
} | |
return $doc->saveHTML(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment