简体   繁体   中英

generate html file and download it with php

First goal: Create an index.html file and create a link to download the generated file

The issue here is when i click to generate new file the downloaded file is always the same and isnt updated

the variable $content has insite an entire html page with <headers><aside> and <sections>

I have the following code

if( empty( $error )){
       echo "<h3>File generated</h3>";
       $my_file = 'index.html';
       if (file_exists($my_file)) {
            if(unlink($my_file)){
            };
            $new_file = 'index.html';
            $handle = fopen($new_file, 'w') or die('Cannot open file:  '.$new_file);
            $data = $content;
            fwrite($handle, $data);
            fclose($handle);

            echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
        } else {
            $new_file = 'index.html';
            $handle = fopen($new_file, 'w') or die('Cannot open file:  '.$new_file);
            $data = $content;
            fwrite($handle, $data);
            fclose($handle);
            echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
        }

hi i think it's will be work if variable $content will be contain correct data and you have permission to read, update, create file. in code I use file_put_contents function for minimize your code

if( empty( $error )){
    echo "<h3>File generated</h3>";
    $my_file = 'index.html';
    file_put_contents($my_file, $content);   
    echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
 }

UPDATE: Are you sure that you have correctly generated content and the $content always contains different value?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM