在 PHP 中打开一个只有部分标题的文件


fopen a file with only part of title in php

所以我正在尝试使用 fopen 从我的服务器调用一个文件,该文件每天都会以相同的部分标题自动加载,但只想获取今天的文件。 例如,如果文件是File20160310.csv我可以通过$file = fopen('file'. $today . '.csv', 'r') or die('cant open file'); $today = date("m-d-y");(但是文件名是File20160310875647.csv日期后的数字是随机的)当我做fopen时,有没有办法从标题中扣除这些数字(我无法更改它锁定的文件)

溶液

解决方案--所以下面的两个答案都有效,但我使用了T0xicCode的答案,在答案中包含.$today.,鸡蛋答案以帮助fgetcsv

$list = glob('ShipToUsShippings'. $today ."*.csv");

$filename = $list[0];

$file = fopen($filename, 'r') 或 die('无法打开文件');

fetcsv($file,1000,",");

($line = fgetcsv(fopen($file))) { echo $line[0]; }

尝试使用 glob() 返回与fileYYYYMMDD*格式匹配的文件列表:

$list = glob('file20160310*.csv');
$file = $list[0] // Assuming there'll only be one match for each day.
$file = fopen($file, 'r') or die('cant open file');

如果每天有多个文件,则可以:

$list = glob('file20160310*.csv');
foreach ($list AS $file) {
    fopen($file, 'r') or die('cant open file');
}

fopen需要文件的确切名称。您需要找到文件的确切名称。您将能够使用 glob 找出文件的完整名称:

$list = glob('file' . $today . '*.csv');
$filename = $list[0];
$file = fopen($filename, 'r') or die('cant open file');

glob返回一个数组,因此您必须索引到其中。如果多个文件与给定的模式匹配,则必须确定要使用哪个文件。