Jump to content

[SOLVED] fopen and fgetcsv


Broxden
 Share

Recommended Posts

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.

Link to comment
Share on other sites

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.

  • Like 1
Link to comment
Share on other sites

  • Broxden changed the title to [SOLVED] fopen and fgetcsv

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...