Instantly share code, notes, and snippets.

@sergejmueller sergejmueller/parse.php
Last active Nov 6, 2016

Embed
What would you like to do?
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