I have a php file in which i am extracting the data from a csv file and making an array and including it to another php which has its html/css to display the retrieved data. Now I have multiple such csv files for which the same task needs to be done.I am currently doing it by manually copying the whole php file into a new php file and changing the file name to be extracted and the array names. Is there a better way of achieving this task?
Asked
Active
Viewed 123 times
-1
-
Any code have you tried so far? – Lovepreet Singh Jun 29 '18 at 05:13
-
Instead of copying to another file why not copying the relevant portion of the codes below the previous one and change the filename? Or make the filename dynamic and loop the code. This will run the operations synchronously. If you want asynchronousity, that's another story. – frz3993 Jun 29 '18 at 05:38
-
Refactoring your code using functions for processing and variables for filename. Foreach loop for all filenames, call function to load and render. Done. – Алексей Присяжный Jun 29 '18 at 06:14
2 Answers
0
Define a class (e.g. Reader) and move the file content extract logic to a method of that class (e.g. getFileContents) and make a call to that class to read file data as below:
$reader = new Reader();
$data = $reader->getFileContents(filename);
So you can repeat the method call logic as many times as you want from as many files as you want as long as your class is accessible from the caller file.
Hope this helps!

dpattayath
- 160
- 5
0
Definitely, you gotta make the code object oriented, as everybody is replying. Or at least, split the code in 2 functions
csvToArray("filename");
display();
Just take a look at this code example: Using php, how can we read 5 rows from a csv file, call another function and then read next 5 rows and repeat this?

Toni Is-here
- 52
- 6