single line text log file parsing - php

So i have a log/txt file wich contains the following :
31 dec. 2014 11:56 - UserA: Hi31 dec. 2014 11:56 - UserB: Hi to you31 dec. 2014 11:56 - UserA: Whats your name?31 dec. 2014 11:57 - UserB: Nancy
Im trying to get this into a more readable format.....
So im trying the following :
<?php
//load the logfile
$txt_file = file_get_contents('test.txt');
$txtfile2 = preg_split( "/ ( |:) /", $txt_file );
$rows = explode("\n", $txtfile2[0]);
foreach($rows as $row => $data)
{
$row_data = explode(':', $data);
$info[$row]['when'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
//display data
echo ' WHEN: ' . $info[$row]['when'] . '<br />';
echo ' WHO: ' . $info[$row]['name'] . '<br />';
echo ' MESSAGE: ' . $info[$row]['description'] . '<br /><br />';
}
?>
This works partially....
When executed the output would be :
WHEN: 31 dec. 2014 11
WHO: 56 - UserA
MESSAGE: Hi
WHEN: 31 dec. 2014 11
WHO: 56 - UserB
MESSAGE: Hi to you
This is close to what i want, but as you can see, because im using the delimiter ":" it will also cut the time and place the minutes in the who.
How can i explode on the second ":" only?
i hope this makes sense?

See how this works for you
<?php
$filename = "logfile.txt"; //data file to open
$fp = fopen( $filename, "r" ) or die("Couldn't open $filename");
while ( ! feof( $fp ) )
{
$line = fgets( $fp, 1024 );
$line_array = preg_split("/[:-]+/", $line);
$line_timestamp = $line_array[0] . ":" . $line_array[1];
$line_user = $line_array[2];
$line_message = $line_array[3];
echo ' WHEN: ' . $line_timestamp . '<br />';
echo ' WHO: ' . $line_user . '<br />';
echo ' MESSAGE: ' . $line_message . '<br /><br />';
}
?>

Related

Why is this foreach loop iterating twice?

Question's in the title really - I have this foreach loop and it appears to be iterating over my array twice.
ob_start();
$array = str_split(strtolower($_GET['text']));
foreach ($array as $char) {
error_log($_GET['text'] . ', ' . sizeof($array) . ', ' . $char);
}
$result = ob_get_contents();
I am finding the code above is producing the following log when passing in the URL like so: index.php?text=Hi
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, h
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, i
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, h
[22-Oct-2018 20:05:37 Europe/London] Hi, 2, i
The debug shows the array to only be 2 long, so I'm really not sure what it could be. Thanks!
After more debugging, I have found the following:
if (!isset($_GET['text'])) {
header('HTTP/1.0 404 Not Found');
die();
}
echo uniqid() . '</br>';
//ob_start();
$total = 0;
$array = str_split(strtolower($_GET['text']));
foreach ($array as $char) {
echo $_GET['text'] . ', ' . sizeof($array) . ', ' . $char . '</br>';
}
//$result = ob_get_contents();
echo $result;
Produces this:
5bce311d3d6bd
Hi, 2, h
Hi, 2, i
But un-commenting the two commented out lines, gives me this:
5bce313b9f29d
Hi, 2, h
Hi, 2, i
Hi, 2, h
Hi, 2, i
I think I perhaps have more to learn about the ob_... functionality?
This following code seems to be consistent and reliable:
if (!isset($_GET['text'])) {
header('HTTP/1.0 404 Not Found');
die();
}
echo uniqid() . '</br>';
ob_start();
$total = 0;
$array = str_split(strtolower($_GET['text']));
foreach ($array as $char) {
echo $_GET['text'] . ', ' . sizeof($array) . ', ' . $char . '</br>';
}
ob_flush();

group archive in php and mysql

I want to create an archive list like this:
2016
July 2016
testing 5 of 16
testing 4 of 16
testing 3 of 16
testing 2 of 16
February 2016
testing 1 of 16
2015
November 2015
testing 1 of 15
but it is showing like this:
2016
July 2016
testing 5 of 16
testing 4 of 16
testing 3 of 16
testing 2 of 16
February 2016
testing 1 of 16
November 2015
testing 1 of 15
2016
July 2016
testing 5 of 16
testing 4 of 16
testing 3 of 16
testing 2 of 16
February 2016
testing 1 of 16
November 2015
testing 1 of 15
2015
July 2016
testing 5 of 16
testing 4 of 16
testing 3 of 16
testing 2 of 16
February 2016
testing 1 of 16
November 2015
testing 1 of 15
This is my source code:
$query = "SELECT * FROM blogs ORDER BY date DESC";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet)){
$newsArray = array();
echo '<ul>' . PHP_EOL;
while ($newsResult = mysql_fetch_array($resultSet)){
$newDate = $newsResult['date'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',strtotime($timePeriod));
$timePeriodM = date('F',strtotime($timePeriod));
/*if (!isset($newsArray[$timePeriod])){
$newsArray[$timePeriod] = array();
}*/
$newsArray[$timePeriod][] = $newsResult;
}
//by year
foreach ($newsArray as $timePeriod => $newsItems){
$timePeriodY = date('Y',strtotime($timePeriod));
echo '<li><strong>' . $timePeriodY . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//by month
foreach ($newsArray as $timePeriod => $newsItems){
echo '<li><strong>' . $timePeriod . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//news items
foreach ($newsItems as $item){
echo '<li>';
echo ''.$item["titlename"].'';
echo '</li>' . PHP_EOL;
}
//end by month
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
//end by year
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
echo '<li> </li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
} else {
echo 'No Blog Found';
}
Please help me with this and thanks in Advance.
You're "grouping" by "F Y" when you should be "grouping" by "Y" and then "F Y"
For example :
$newsArray[$timePeriod][] = $newsResult;
Should be something like
$newsArray[$timePeriodY][timePeriod][]= $newsResult;
Your code will then become:
$query = "SELECT * FROM blogs ORDER BY date DESC";
$resultSet = mysql_query($query);
if (mysql_num_rows($resultSet)){
$newsArray = array();
echo '<ul>' . PHP_EOL;
while ($newsResult = mysql_fetch_array($resultSet)){
$newDate = $newsResult['date'] ;
$timePeriod = date('F Y ',strtotime($newDate));
$timePeriodY = date('Y',strtotime($timePeriod));
$timePeriodM = date('F',strtotime($timePeriod));
$newsArray[$timePeriodY][$timePeriod][] = $newsResult;
}
//by year
foreach ($newsArray as $timePeriodY => $newsItems){
echo '<li><strong>' . $timePeriodY . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//by month
foreach ($newsItems as $timePeriod => $items){
echo '<li><strong>' . $timePeriod . '</strong>' . PHP_EOL;
echo '<ul>' . PHP_EOL;
//news items
foreach ($items as $item){
echo '<li>';
echo ''.$item["titlename"].'';
echo '</li>' . PHP_EOL;
}
//end by month
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
//end by year
echo '</ul>' . PHP_EOL;
echo '</li>' . PHP_EOL;
}
echo '<li> </li>' . PHP_EOL;
echo '</ul>' . PHP_EOL;
} else {
echo 'No Blog Found';
}

How to get array from API

I want to get the episode number and Released from
http://www.omdbapi.com/?t=the+walking+dead&season=6&r=json
but I don't know how to extract arrays from the api.
Can someone help me?
My code is:
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
}
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json = file_get_contents("http://www.omdbapi.com/?t=$title2&season=6&r=json");
$details = json_decode($json);
if ($details->Response == 'True') {
echo 'There are ' . count($details->Episodes) . ' episodes<br />';
foreach ($details->Episodes as $key => $episode) {
echo 'Episode criteria number is ' . ($key + 1) . '<br />';
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released: ' . $episode->Released . '<br />';
}
}
<?php
$title = 'the+walking+dead';
$title2 = urlencode($title);
$json=file_get_contents("http://www.omdbapi.com/t=$title2&season=6&r=json");
$details=json_decode($json);
if($details->Response=='True')
{
$episodios=$details->Episodes;
foreach ($episodios as $episode) {
echo 'Episode Number: ' . $episode->Episode . '<br />';
echo 'Released Date: ' . $episode->Released . '<br />';
}
}
?>

PHP substring extrac and calulate

I'm using to show exif data of a picture.
this is the code
<?php
$filename = "http://www.rallyfun.net/images/20140921231511_img_7369.jpg";
$exif = exif_read_data($filename, 0, true);
echo "Exposure: " . $exif["EXIF"]["ExposureTime"] . " sec.<br />";
echo "F: " . $exif["EXIF"]["FNumber"] . "<br />";
echo "ISO: " . $exif["EXIF"]["ISOSpeedRatings"] . "<br />";
?>
this is the result:
Exposure: 1/6400 sec.
F: 63/10 sec.
ISO: 1000
the result is ok except for the aperture: it must be displayed as (in this case) 6.3 so i need to divide the first number (63) with the number after the "/" (10).
how?
U can use explode for this.
$tmp = explode('/', str_replace(' sec.', '', $exif["EXIF"]["FNumber"]));
echo "F: " . ($tmp[0]/$tmp[1]) . "sec<br />";
You can use this code to display aperture:
preg_match('/([0-9]+)\/([0-9]+)/',$exif["EXIF"]["FNumber"],$m);
if($m[1] && $m[2])
{
$newaperture = $m[1]/$m[2];
echo $newaperture;
}
Try the following :
$n = $exif["EXIF"]["FNumber"];
$whole = floor($n); // 63
$fraction = $n - $whole; // .10
$result=$whole/$fraction;

Command-line PHP truncating date("c")

Here's my PHP code for a shell-script:
#!/usr/bin/php -q
<?php
$user = get_current_user();
$line = date("c") . " - " . $user + "\r\n";
echo "---------------------\n";
echo "user => $user\n";
echo "---------------------\n";
echo "date('c') => " . date("c") . "\n";
echo "---------------------\n";
echo "date('Ymd') => " . date("Ymd") . "\n";
echo "---------------------\n";
echo "line => $line\n";
echo "---------------------\n";
echo date("c") . " - " . $user + "\n";
echo "---------------------\n";
echo date("c") . $user + "\n";
echo "---------------------\n";
echo date("c") . " - " . "\n";
echo "---------------------\n";
$ret = file_put_contents("/var/lib/foo/bar/test.txt", $line, FILE_APPEND);
echo "file_put_contents => $ret\n";
?>
When I run it, I get this output:
roffle:/var/lib/foo/bar # php Test.php
---------------------
user => wwwrun
---------------------
date('c') => 2014-07-27T16:39:34-04:00
---------------------
date('Ymd') => 20140727
---------------------
line => 2014
---------------------
2014---------------------
2014---------------------
2014-07-27T16:39:34-04:00 -
---------------------
file_put_contents => 4
roffle:/var/lib/foo/bar #
Why is $line truncated along with the first two calls to echo date("c") and why is the third call to date("c") okay?
Looks like you've just mixed up + with the . for concatenation in the lines in question.

Categories