Skip to content

Instantly share code, notes, and snippets.

@sergejmueller
Last active November 6, 2016 10:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sergejmueller/8d7f1385ab6600537148841300acd48d to your computer and use it in GitHub Desktop.
Save sergejmueller/8d7f1385ab6600537148841300acd48d to your computer and use it in GitHub Desktop.
Parse User-Agents from a text file and extract Browser/Platform data
<?php
# Enable errors
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
# Push up memory
ini_set( 'memory_limit', '128M' );
ini_set( 'max_execution_time', 300 );
# Init
$lines = 0;
$data = array(
'platform' => array(),
'browser' => array()
);
$idents = array_keys( $data );
# Read log
$file = fopen( 'log.txt', 'r' );
# Loop lines
while( ! feof( $file ) ) {
$lines ++;
$capabilities = get_browser( fgets( $file ) );
$browser = $capabilities->parent;
$platform = $capabilities->platform;
foreach( $idents as $ident ) {
if ( isset( $data[$ident][${$ident}] ) ) {
$data[$ident][${$ident}] ++;
} else {
$data[$ident][${$ident}] = 1;
}
}
}
# Close file
fclose( $file );
# Sort arrays
foreach( $idents as $ident ) {
arsort($data[$ident], SORT_NUMERIC);
echo sprintf(
'<h1>%s</h1>',
ucfirst($ident)
);
foreach( $data[$ident] as $key => $value ) {
echo sprintf(
'%s &#8594; %s (%s%%)<br />',
$key,
$value,
round( ($value * 100 / $lines), 2)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment