Loop through XML elements using PHP

If you don’t know the absolute path of an element in your xml file the using xpath and ‘//’ acts as a wildcard (similar to ‘..’ in as3 i guess) you can run a loop and return all values for those elements.

Handy for this likes RSS feeds or KML files ect.

<?php

$xml = simplexml_load_file('my.xml');

	foreach ($xml->xpath('//xmlnode')  as $node) {
    	echo "\t node: $node <br />\n";

	}
?>

Handy Hint: AMFPHP to Flash Character Encoding

If you’ve ever used AMFPHP to connect your DB into Flash, you may stumble across weird characters being output! eg: – replaces the ’. The simple explanation is that the PHP is decoding it wrong.

Forget about preg_replace(), all you need to do is update your amfphp/gateway.php file to decode, encode in UTF-8.


$gateway->setCharsetHandler("utf8_decode", "UTF-8", "UTF-8");

and walla no more annoying characters sent from AMFPHP.

PHP Snippet – Get Yesterdays date

This is a simple function that returns yesterdays date. Simple but handy.

function yesterday()
{
 $yesterday = date("Y:m:d",mktime(0,0,0,date("m") ,date("d")-1,date("Y")));
 return $yesterday;
}

PHP Snippet – Time difference between 2 date/time stamps.

In a recent project I needed to capture how long the user spent on the application, it was not expected they would spend days on it so it return hours minutes seconds which can be saved to a database.
So basically here is a function to do that…

//
echo getTimeDifference("2010-02-26 18:35:36");

function getTimeDifference($start_time){

 //convert $start_time into a usable string
 $tempStart = preg_replace('/(\d{2})-(\d{2})-(\d{2})(.*)/', '$1:$2:$3:$4',$start_time);
 $tempStart=explode(":",$tempStart);

 $year = $tempStart[0];
 $month= $tempStart[1];
 $day = $tempStart[2];
 $hour = $tempStart[3];
 $minute = $tempStart[4];
 $second = $tempStart[5];

 //set the end time as current time
 $timesEnd = date("Y:m:d:H:i:s");
 $tempEnd=explode(":",$timesEnd);

 $year1 = $tempEnd[0];
 $month1= $tempEnd[1];
 $day1 = $tempEnd[2];
 $hour1 = $tempEnd[3];
 $minute1 = $tempEnd[4];
 $second1 = $tempEnd[5];

 $countdown_date = mktime($hour, $minute, $second, $month, $day, $year);
 $countdown_date1 = mktime($hour1, $minute1, $second1, $month1, $day1, $year1);

 $diff = $countdown_date1 -$countdown_date ;
 if ($diff < 0)
 $diff = 0;
 $dl = floor($diff/60/60/24);
 $hl = floor(($diff - $dl*60*60*24)/60/60);
 $ml = floor(($diff - $dl*60*60*24 - $hl*60*60)/60);
 $sl = floor(($diff - $dl*60*60*24 - $hl*60*60 - $ml*60)
 );

 $timeDifference = "$hl:$ml:$sl";

 return $timeDifference;
 }