Reputation: 63
I'm currently trying to make my script dynamic and looking for a way to grab my file data with wildcards.
This is my old code:
#process .csv into the database
if(($handle = fopen("9_filename.csv", "r")))
Here I just grab a file through a string. Works fine. But it's static and I need to process 20 files per week at once, which change the calendar week in the file name.
So after some research I found the "glob" function, which allows me to set wildcards. So I assign a variable with the "glob" function. A var_dump returns the correct file name "9_filename.csv". So the string exists.
This is my new code:
#variables
$file = glob("*_filename.csv");
#process .csv into the database
if(($handle = fopen($file, "r")))
Unfortunately as a result I get the following error:
Warning: fopen() expects parameter 1 to be a valid path, array given in
Upvotes: 0
Views: 876
Reputation: 16103
Because glob
finds all files matching pattern, it must return an array.
And fopen can only handle one at a time, so you need to feed them one at a time:
#variables
$files = glob("*_filename.csv");
foreach($files as $file){
#process .csv into the database
if(($handle = fopen($file, "r")))
}
Upvotes: 4
Reputation: 80
glob()
functions return an array of filenames or directories matching a specified pattern.
So once you get an array you need to loop through each array.
In that case you can then use
if(($handle = fopen("9_filename.csv", "r")))
where 9_filename.csv
will be one the array value.
Upvotes: 0