0

Hello,

I have csv filename with date. Everyday i have same csv file with respective date.
I need to read filename (everyday date changes in filename) and do operation.

For example, I have file "cells_20140106_165532.csv". I did like this to read it in general:

$filename = "cells_".date('Ymd_hmi').".csv";
$file_contents = file_get_contents($filename);
$importcsvsql = "";

//error: cells_20140114_110109.csv

It is taking current date instead of filename's date. It is generating empty file "cells_20140114_110109.csv"

Thanks in advanced.

Edited by PriteshP23: code

4
Contributors
8
Replies
26
Views
3 Years
Discussion Span
Last Post by diafol
0

When you call date('Ymd_hmi') it's getting the current execution date and time. What I would recommend doing is getting the most recent file by listing the contents of the directory, finding out the most recent file (In this case simply ordering by filename and taking the last one in the list should be fine) and then reading that one.

0

How to make it general so that it take the value which is in filename?

There is single file. So, no need to find latest date or deleting other files like that.

Thanks in advanced for your time and input.

0

if its single file then when you store it, keep one name say cells.csv

You should updates with same name and read with same name.

0

if its single file then when you store it, keep one name say cells.csv

No, it is not possible because i can't change the filename. In addition, i have to read filename with date and later display the time from it.

0

Read the directory with glob() or similar and get filenames into an array - you can look that up yourself.

You can search with preg functions (regex):

cells_20140106_165532.csv

I think would be:

cells_(\d{8})_(\d{6}).csv

So the first captured group would be the "Ymd" and the second "His"

0

Finally, it works..!

foreach (glob("cells_*.csv") as $filename)
{
    list(, $date, $time) = explode('_', substr($filename, 0, -4));

    $date = substr($date, 0, 4) . '/'  . substr($date, 4, 2) . '/'  . substr($date, 6, 2);
    $time = substr($time, 0, 2) . ':'  . substr($time, 2, 2) . ':'  . substr($time, 4, 2);

    echo "The datetime for $filename is $date at $time<br />";
}

Thank you all.

0

OK, for completeness, here's mine...

foreach (glob("cells_*.csv") as $haystack)
    if ( preg_match('/cells_(\d{8})_(\d{6})\.csv/', $haystack, $matches) )
        echo "The datetime for $haystack is {$matches[1]} at {$matches[2]}<br />";

but without the rearranging of date/time

[However, preg is slow and you solution although it uses more function calls, will be quicker]

Edited by diafol

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.