Broxden 3 Posted November 24, 2020 Hello I hope someone can help me. I'm trying to make an HTML table from a CSV file. I have a test CSV file and a test PHP script, both of which work as expected when I upload them into the root of public_html. What I want to do is upload the file into my page using a Files field and then access the CSV data to produce an HTML table via my template. This code works when I place it in the root of my site... <?php echo "<html><body><table>\n\n"; $f = fopen("site/assets/files/1619/dundee.csv", "r"); while (($line = fgetcsv($f)) !== false) { echo "<tr>"; foreach ($line as $cell) { echo "<td>" . htmlspecialchars($cell) . "</td>"; } echo "</tr>\n"; } fclose($f); echo "\n</table></body></html>"; ?> However, when I add the code to my template as follows, the page does not render at all. Am I doing something wrong? <h2>Perth Memberships</h2> <div class="uk-overflow-auto"> <table class="uk-table uk-table-striped"> <?php $f = fopen("site/assets/files/1619/dundee.csv", "r"); while (($line = fgetcsv($f)) !== false) { echo "<tr>"; foreach ($line as $cell) { echo "<td>" . htmlspecialchars($cell) . "</td>"; } echo "</tr>\n"; } fclose($f); ?> </table> </div> I also tried using $files->url/dundee.csv to get file path but that didn't help. Share this post Link to post Share on other sites
MoritzLost 783 Posted November 24, 2020 The reason it's not working is that you're giving fopen a relative path. This works fine with your test file if it's placed in the webroot, since the path is relative to that. But inside a template file, the relative path does not resolve correctly. For a static file, you can use $config->paths to retrieve an absolute base path that will always work: $f = fopen($config->paths->files . "1619/dundee.csv", "r"); If you want to read a CSV file uploaded to a page field, you can use Pagefile::filename instead: $filename = $page->your_csv_field->filename(); $f = fopen($filename, "r"); Make sure your CSV field is set to single file output. If your field allows multiple files, use $page->your_csv_field->first()->filename() instead. 1 Share this post Link to post Share on other sites
Broxden 3 Posted November 24, 2020 Thank you very much for taking the time to reply. I used your suggestion for a CSV file uploaded to a page field and it works perfectly! 1 Share this post Link to post Share on other sites
adrian 11,944 Posted November 25, 2020 @Broxden - if users are able to upload different CSV files, you might at some point come across an issue with the BOM, so it might be worth implementing this: https://stackoverflow.com/a/51789304/1524576 Share this post Link to post Share on other sites
Broxden 3 Posted November 27, 2020 Thank you for that additional information, it's much appreciated. Share this post Link to post Share on other sites