Saturday, June 13, 2009

PHP - XML Multi-Page Hit Counter Development

I am developing a hit counter with PHP that tracks hits on a page by page basis with an XML file. This version is for PHP 5. So far, it only edits existing entries in the XML. If it is going to work on a database driven site, I need to write in some validation and more complex XML editing script. If you improve on it, please send me your updates :

hitcounter2.php :


<?php
#GET THE XML FILE
$xml = simplexml_load_file(SITEROOT.'hitcounter2.xml');

#LOOP TO FIND THE ID
foreach($xml->hitcounter->page as $page)
{
if ($page['id'] == $page_id)
{
echo $page['num_hits'];
//$num_hits = $page['num_hits'] + 1;
$page['num_hits'] = $num_hits;
break;
}
}

#UPDATE THE XML FILE
file_put_contents(SITEROOT.'hitcounter2.xml', $xml->asXml());
?>

hitcounter2.xml :

<?xml version="1.0" encoding="utf-8"?>
<hitcounter>
<page>
<id>1</id>
<num_hits>21</num_hits>
</page>
<page>
<id>2</id>
<num_hits>22</num_hits>
</page>
<page>
<id>3</id>
<num_hits>23</num_hits>
</page>
</hitcounter>

Place this on any PHP page in your site:

<?php
include (SITEROOT.'hitcounter2.php?page_id=3'); // change the page_id for each page
?>

2 comments:

Unknown said...
This comment has been removed by the author.
Unknown said...

PHP hitcounter2.php doesn't worked for me, till I made some changes:

$page_id = $_GET['page_id'];
foreach ($xml as $page)
{
if ($page->id == $page_id)
{
echo $page->num_hits;
$num_hits = $page->num_hits + 1;
$page->num_hits = $num_hits;
break;
}
}