Adding event tags to links

3 posts by 2 authors in: Forums > CMS Builder
Last Post: August 29, 2016   (RSS)

By Djulia - August 29, 2016 - edited: August 29, 2016

Hi Tim,

You can use DOMDocument::loadHTML

$doc = new DOMDocument;
$doc->loadHTML(utf8_decode('<div>'.$record['content'].'</div>'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  
// find all anchors
foreach ($doc->getElementsByTagName('a') as $anchor) {
  if ($anchor->hasAttribute('class') && $anchor->hasAttribute('title')) {
    $attr = $anchor->getAttribute('class');
    if ($attr != 'trackThis') { continue; }
    $anchor->setAttribute("onClick", "ga('send', 'event', { eventCategory: 'Internal Page Links', eventAction: 'click', eventLabel: ".$anchor->textContent.", eventValue: Sample Title})");
  }
}
$html = utf8_encode($doc->saveHTML());
$new_html = preg_replace("/(^<div[^>]*>|<\/div>$)/i", "", $html);
echo $new_html;

LIBXML_HTML_NODEFDTD is only available in Libxml 2.7.8 and LIBXML_HTML_NOIMPLIED is available in Libxml 2.7.7...
http://www.php.net/manual/en/libxml.constants.php

Cheers,

Djulia

By Toledoh - August 29, 2016

Thanks so much Djulia.  I'll look into getting that on my server and test it!

Cheers,

Tim (toledoh.com.au)