Google Analytics event tracking with PHP in html_output - php

I'm getting category from my database using PHP and I want to use it inside Google Analytics event tracking code. The problem is that events are not being recorded in Google Analytics.
Here are some code snippets from my project:
1)
$docs = array();
while ($row = mysql_fetch_assoc($result)) {
$doc = array();
$doc['my_tel'] = $row['my_tel'];
$doc['my_category'] = $row['my_category'];
$docs[] = $doc;
}
mysql_free_result($result);
2)
<?php
$html_output = '';
foreach ($docs as &$d) {
$html_output .= '<div>' .
'<img src="call.png" width="65px" height="35px" border="0">' .
'</div>';
}
echo $html_output;
?>

If you have a look at the console of your browser there might be a JavaScript error, because the second parameter of _gaq.push is not wrapped with quotes.
Try this:
<?php
$html_output = '';
foreach ($docs as &$d) {
$html_output .= '<div>' .
'<img src="call.png" width="65px" height="35px" border="0">' .
'</div>';
}
echo $html_output;
?>

Looking at your append to $html_output, it appears you're not enclosing the category within single quotes in the resultant javascript output.
Assuming for example my_tel was 01234567890 and category was 'Category 1' the output from the code above would be:
<div><img src="call.png" width="65px" height="35px" border="0"></div>
Perhaps try (note additional escaped quotes around category:
'<a href="tel:' . $d['my_tel'] . '" onClick="_gaq.push([\'_trackEvent\', \'' . $d['my_category'] . '\', \'Event Action\',...
--dan

Related

Auto increment through a php loop

I have a case where I am using the code below to populate a template of sorts. Within the templates' javascript I would individually check the data attribute field I setup, essentially causing me to have multiple JS files instead of one that is shared. I then thought I could use a generic name field too, but prepend a number through the loop.
For example, with the line of code below where the `name="testField". I want to see if there is a way that I can add a number, but auto increment it through the loop with php.
Is this possible?
echo '<div class="markerItem" name="testField' . $number . '" "data-marker="' . $marker_data . '">';
PHP Code
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
if ($marker_stmt = $con->prepare($sql_marker)) {
$marker_stmt->execute();
$marker_rows = $marker_stmt->fetchAll(PDO::FETCH_ASSOC);
echo '<div id="projMarker">';
foreach ($marker_rows as $key=>$marker_row) {
$marker_solution = $marker_row['solution'];
$maker_item = $marker_row['subSolution'];
$marker_data = $marker_row['subSolution'];
echo '<div class="markerItem" name="testField_'.$key.'" data-marker="' . $marker_data . '">';
echo $marker_item;
echo '</div>';
}
}
echo '</div>';
Using this, $key is assigned from the array index which will be a number starting from 0 and ending at count($marker_rows)-1.
Suprisingly, I couldn't find an appropriate duplicate for this.
You can easily increment or decrement variables in PHP.
$number = 0;
foreach ($marker_rows as $marker_row) {
...
$number++; // $number will now be $number+1
}
You can use $number++ directly in your attribute (if concatenating) as this will return the current $number then increment the value.

Loop through two DOMNodeLists at once using DOMDocument class

I got an error saying
Object of class DOMNodeList could not be converted to string on line
This is the line which contains the error:
$output .= '<li><a target="_blank" href="' . $postURL . '">' .
$title->nodeValue . '</a></li>';
DOM
My code:
$postTitle = $xpath->query("//tr/td[#class='row1'][3]//span[1]/text()");
$postURL = $xpath->query("//tr/td[#class='row1'][3]//a/#href");
$output = '<ul>';
foreach ($postTitle as $title) {
$output .= '<li><a target="_blank" href="' . $postURL . '">' . $title->nodeValue . '</a></li>';
}
$output .= '</ul>';
echo $output;
How can I resolve the error?
You're fetching two independent node list from the DOM, iterate the first and try to use the second one inside the loop as a string. A DOMNodeList can not be cast to string (in PHP) so you get an error. Node lists can be cast to string in Xpath however.
You need to iterate the location path that is the same for booth list (//tr/td[#class='row1'][3]) and get the $title and $url inside the loop for each of the td elements.
$posts = $xpath->evaluate("//tr/td[#class='row1'][3]");
$output = '<ul>';
foreach ($posts as $post) {
$title = $xpath->evaluate("string(.//span[1])", $post);
$url = $xpath->evaluate("string(.//a/#href)", $post);
$output .= sprintf(
'<li><a target="_blank" href="%s">%s</a></li>',
htmlspecialchars($url),
htmlspecialchars($title)
);
}
$output .= '</ul>';
echo $output;

PHP Read XML Podcast RSS Feed

OK, so, I'm creating a page for a friend's podcast site that lists out all of the episodes to his podcast(s). Essentially, all I'm looking for is how to read the RSS Feed. Parse out the Nodes, and display the information on the screen. (eventually, I'm going to create a player that will play the episodes, but that's much later)
This is how I'm reading the RSS Feed (which is to one of my shows - for testing purposes).
click to see My Feed
<?php
//Errors:
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$rss = new DOMDocument();
$rss->load('http://tbpc.podbean.com/feed/');
$feed = array();
foreach ($rss->getElementsByTagName('item') as $node) {
$item = array (
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'link' => $node->getElementsByTagName('link')->item(0)->nodeValue,
'desc' => $node->getElementsByTagName('description')->item(0)->nodeValue,
'guid' => $node->getElementsByTagName('guid')->item(0)->nodeValue,
'enclosure' => $node->getElementsByTagName('enclosure')->item(0)->nodeValue,
);
array_push($feed, $item);
}
$limit = 1;
for($x=0;$x<$limit;$x++) {
$title = str_replace(' & ', ' & ', $feed[$x]['title']);
$link = $feed[$x]['link'];
$description = $feed[$x]['desc'];
$short = substr($description, 0, strpos( $description, '<'));
$file = $feed[$x]['guid'];
echo '<p><strong>'.$title.'</strong></p>';
echo '<p>'.$description.'</p>';
echo '<p>'.$short.'</p>';
echo '<p>'.$file.'</p>';
}
?>
The problem is - is that I have no idea how to get the information out of the attribute url of the enclosure node so I can display it on the page with the rest of the information (this will come in handy when I make the player - eventually).
SO! How do I get the url attribute from the enclosure node? Am I going about this all wrong?
Any helpful hints would be appreciated. Thanks.
Apologies if you're determined to use DOMDocument() in this, but since nobody has posted an answer so far...here's a script which uses simple_xml_load_file(), which I found quite easy to get to grips with.
<?php
$rss_array = array('http://rss.computerworld.com/computerworld/s/feed/topic/231', 'http://rss.computerworld.com/computerworld/s/feed/topic/230', 'http://rss.computerworld.com/computerworld/s/feed/topic/66', 'http://www.engadget.com/rss.xml', 'http://feeds.webservice.techradar.com/rss/new', 'http://feeds.arstechnica.com/arstechnica/index', 'http://www.notebookcheck.net/News.152.100.html', 'http://electronista.feedsportal.com/c/34342/f/626172/index.rss', 'http://www.anandtech.com/rss/pipeline/', 'http://www.digitimes.com/rss/daily.xml', 'http://feeds.feedburner.com/TechCrunch/', 'http://feeds2.feedburner.com/ziffdavis/pcmag/breakingnews', 'http://feeds.feedburner.com/Liliputing', 'http://feeds.slashgear.com/slashgear', 'http://feeds.feedburner.com/GizmagEmergingTechnologyMagazine', 'http://www.zdnet.com/news/rss.xml', 'http://feeds.feedburner.com/mobilityupdate', 'http://www.techmeme.com/feed.xml', 'http://www.notebookreview.com/rss.xml');
for ($i=0; $i<count($rss_array); $i++ ) {
$rssfeed = simplexml_load_file($rss_array[$i]);
foreach ($rssfeed->channel as $channel) {
echo '<h1>' . htmlentities($channel->title) . '</h1>';
echo '<p>' . htmlentities($channel->description) . '</p>';
echo '<p><a href="' . htmlentities($channel->link) . '">' .
htmlentities($channel->link) . '</a></p>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($channel->link) . '\')">';
echo '<ul>';
foreach ($channel->item as $item) {
echo '<li><a href="' . htmlentities($item->link) . '">';
echo htmlentities($item->title) . '</a>';
// echo htmlentities($item->description) . '</li>';
echo '<input type="button" value=" >>> " onClick="downloadFileViaAjax(\'' . htmlentities($item->link) . '\')"></li>';
}
echo '</ul>';
}
}//fur ( $rss_array++ )
?>
Nodes have an getAttribute() method. So you can use:
$node->getElementsByTagName('enclosure')->item(0)->getAttribute('url')
But here is another and more comfortable way to fetch nodes and values from an XML DOM: Use Xpath. See this answer: https://stackoverflow.com/a/20225186/2265374
The $node->getElementsByTagName('enclosure')->item(0) will result in an error if no element is found (same goes for SimpleXML btw). If the node list is cast to string in Xpath, the result is just an empty string and no error is triggered.
You can directly fetch attributes this way, too. Like the url attribute of the enclosure element:
echo 'Enclosure Url: ', $xpath->evaluate('string(enclosure/#url)', $rssItem), "\n";

Print specific array value via function argument

$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $menu[$key] . '">' . $menu[$key] . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu[1]); ?>
What i basically want to do is to pass a specific array value when i'm echoing out the menu.
I'm building a single page website with anchors and i want to pass value's so i can echo out the "top"-link.
I'm stuck at the point on how to pass the $key value trough the function.
**edit: I'm trying to print specific links. I want a function that is able to print out an link but i want to specify the link to print via the function argument.
for example:
<?php echo main_menu($key = '0'); ?>
result:
prints url: top
<?php echo main_menu($key = '2'); ?>
result:
prints url: photography
**
(A lack of jargon makes it a bit harder to explain and even harder to google.
I got my books in front of me but this is taking a lot more time than it should.)
You either need to pass the entire array and loop, or pass a single array item and not loop:
Single Item:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
$return .= '<a class="menu" href="index.php#' . $menu . '">' . $menu . '</a>' . PHP_EOL .'';
$return .= '</div>';
return $return;
}
echo main_menu($menu[1]);
Entire Array:
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach($menu as $value) {
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
echo main_menu($menu);
You don't need $menu[$key] just use the $value.
Should you not just be using $value inside your loop? And passing the entire array rather than one item of the $menu array?
$menu = array(
0 =>'top',
1 =>'photography',
2 =>'about'
);
<?php
function main_menu ($menu) {
$return = '<div class="menu_entry">' . PHP_EOL .'';
foreach( $menu as $key => $value)
{
$return .= '<a class="menu" href="index.php#' . $value . '">' . $value . '</a>' . PHP_EOL .'';
}
$return .= '</div>';
return $return;
}
?>
<?php echo main_menu($menu); ?>
Try:
echo main_menu($menu); // You will get your links printed
Instead of
echo main_menu($menu[1]); // In this case error is occured like : **Invalid argument supplied for foreach**
NOTE: You can use $value instead of $menu[$key]

extracting values from associative array in php

I have an array in the following format.
$data = array(
1=>array('img'=>'1.png','title'=>'title1','desc'=>'desc1'),
2=>array('img'=>'2.png','title'=>'title2','desc'=>'desc2'),
1=>array('img'=>'3.png','title'=>'title3','desc'=>'desc3'),
);
Here is the final output I need,
<img src="1.png">
<h1>title1</h1>
<p>desc1</p>
<img src="2.png">
<h1>title2</h1>
<p>desc2</p>
.........
How can i create it? Thanks for the help.
Use a foreach loop, like so:
foreach( $data as $item) {
echo '<img src="' . $item['img'] . '">';
echo '<h1>' . $item['title'] . '</h1>';
echo '<p>' . $item['desc'] . '</p>';
echo "\n";
}
Simply use your array like
foreach($data as $item){
echo $item['title'];
.....
}
This will give you the logic. Now you can apply the img and tags properly
<?php
foreach($data as $item) {
?>
<img src="<?=$item['img']?>">
<h1><?=$item['title']?></h1>
<p><?=$item['desc']?></p>
<br />
<?php } ?>
Another option here.

Categories