Lohardt
Lohardt

Reputation: 1045

Parsing a text file to create a useful log file

On an ubuntu 10.04 server, i have a 30mb log file from php.

Unfortunately the log looks like this:

...)
Array
(
    [calid] => 3114
    [email] => [email protected]
    [firstname] => John
    [lastname] => Smith
    [address] => Lorem ipsum.
    [city] => Lorem
    [postcode] => 1345
    [date] => 01-12-2013
)
Array
(
    [calid] => 3111
    [firstname] => Lisa
    [lastname] => Smith
    [address] => Lorem ipsum.
    [city] => Lorem
    [postcode] => 4110
    [email] => [email protected]
    [phone] => 12345678
    [age] => 24
    [gender] => female
    [customer] => true
    [terms] => true
    [newsletter] => true
    [date] => 01-12-2013
)
Array
(...

How can i parse this into something more useful? A csv would be nice.

Upvotes: 0

Views: 95

Answers (1)

ilpaijin
ilpaijin

Reputation: 3695

A raw idea that may be helpful as a start:

$log = fopen('yourlogfile.log', 'r');

$data = array();
$key = 0;

while (!feof($log)) 
{
    $line = fgets($log);

    if(false !== strpos($line, 'Array'))
    {
        $key++;
        $data[$key] = array();
    }

    $pattern = '/\[(.*?)\] => (.+)/';
    preg_match_all($pattern, $line, $matches);

    if(!empty($matches[0]))
    {
        $data[$key][$matches[1][0]] = $matches[2][0];
    }
}
fclose($log);

// var_dump($log);

$csv = fopen('yourtarget.csv', 'w+');

for( $i = 1; $i <= count($data); $i++) 
{
    fputcsv($csv, $data[$i]);
}
fclose($csv);

Upvotes: 1

Related Questions