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.

Recommended Answers

All 8 Replies

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.

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.

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.

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.

Member Avatar for diafol

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"

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.

Member Avatar for diafol

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]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.