Name a csv file

Asked

Viewed 43 times

1

I on a site I develop backup data in csv my problem and that if I want to recover the backup (through the site ) as I have a folder with several csv I can’t know which was the last one that was created.

Does anyone know of any way that I can verify the date that is in the name because the filename is of this genus nome_2015-11-13_01.42.22_.csv

Thank you

  • It’s a csv a day or power has more?

  • If the default format is this for everyone, you can use regex to filter the name date, see: https://ideone.com/rionwn

3 answers

2


Use the function glob() to list all csv files, do this get the date contained in the name, with the explode() the index containing ta is 1 and the time the 2, swap out the . for :, add this new string to the array $novo then sort in decreasing form with rsort()

<?php
error_reporting(E_ALL|E_STRICT);

$arquivos = glob('temp/*.csv');
$novo = array();
foreach ($arquivos as $item){
    $datahora = explode('_', $item);
    $novo[] = $datahora[1] .' '. str_replace('.', ':', $datahora[2]);
}

rsort($novo);
$backup = array_shift($novo);
echo 'Backup mais recente realizado em: '.  $backup;

The exit is something like:

Array
(
    [0] => 2015-11-14 01:42:23
    [1] => 2015-11-14 01:42:22
    [2] => 2015-11-13 01:42:22
    [3] => 2015-11-12 01:42:22
    [4] => 2015-11-10 01:42:22
    [5] => 2015-10-13 01:42:22
)
Backup mais recente realizado em 2015-11-14 01:42:23

1

Browse the directory of your backups and sort the files by creation date.

<?php

$arquivos = array();
$diretorio = 'caminho/da/pasta/de/backup/';
$manipulador  = opendir($dir);
while (false !== ($arquivo = readdir($manipulador))) {
    $arquivos[] = $arquivo;
}

$listaArquivos = array();
foreach ($arquivos as $arquivo) {
    $listaArquivos[filemtime($arquivo)] = $arquivo;
}

ksort($listaArquivos);
var_dump($listaArquivos);

?>

1

For lists the files exist more than one way, as pointed out in the other answers.

Either way you will have to extract from the name the portion that refers to date, by position or with regular expression.

$arquivo = 'nome_2015-11-13_01.42.22_.csv';
$prefixo = 'nome_';
$dataHora = substr(strlen($prefixo), 19);

To convert to date you have two ways:

1 - with the function DateTime::createFromFormat (required PHP >= 5.3.0), in which case an object will be returned DateTime

DateTime::createFromFormat('Y-m-d_H.i.s', $dataHora)

2 - with the function strtotime, will need to make a format conversion, changing the _ for T, according to the accepted [composite formats], which returns a time stamp:

strtotime($dataHora, str_replace('_', 'T', $dataHora));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.