问题
I am trying to download a file from a SFTP server. I have managed to connect to it and download the files. The problem is that the file in the server will be updated daily and part of the filename is the exact time when it is generated which is unpredictable.
How can I implement my PHP script so it downloads any XML file which name starts with a certain pattern but I don't know the exact full name?
回答1:
You have to retrieve a list of all files in the remote directory using Net_SFTP::nlist.
Then you iterate the list, finding a file name that matches your requirements.
Then you download the selected file using Net_SFTP::get.
include("Net/SFTP.php");
$sftp = new Net_SFTP("host");
if (!$sftp->login("username", "password"))
{
die("Cannot connect");
}
$path = "/remote/path";
$list = $sftp->nlist($path);
if ($list === false)
{
die("Error listing directory ".$path);
}
$prefix = "prefix";
$matches = preg_grep("/^$prefix.*/i", $list);
if (count($matches) != 1)
{
die("No file or more than one file matches the pattern: ".implode(",", $matches));
}
$matches = array_values($matches);
$filename = $matches[0];
$filepath = $path."/".$filename;
if (!$sftp->get($filepath, $filename))
{
die("Error downloading file ".$filepath);
}
回答2:
Well a regular expression (abbreviated regex or regexp and sometimes called a rational expression) is a sequence of characters that forms a search pattern, mainly for use in pattern matching with strings, or string matching, i.e. "find and replace"-like operations and would be perfect for what you need. Here is more background on regex: http://en.m.wikipedia.org/wiki/Regular_expression
For your testing : http://www.phpliveregex.com
here is an example: http://php.net/manual/en/function.preg-match.php
<?php
$subject = "abcdef";
$pattern = '/^def/';
preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
?>
来源:https://stackoverflow.com/questions/30402015/downloading-file-matching-pattern-using-phpseclib