0

I want to create a custom function that will write the new blog entry! I need to get existing data from the textfile than get the data from the input form and write all the data back to the file

          <div class="title">
            <label for="Title">Title:</label>
            <input type="text"  name="title" required>
          </div>

          <div class="message">
            <label for="Message">Message:</label>
            <input type="text" name="message" required>
          </div>

          <input type="submit" class="btn btn-default" name="mysubmit">
        </form>

<?php  

function writeToBlog($thisTitle, $thisMessage)
{
    
    $thisTitle = $_POST['title'];
    $thisMessage = $_POST['message'];
    echo "$thisTitle";
    echo "$thisMessage";
$handle = fopen("blogfile.txt", "r");
if($handle){
while(!feof($handle)){
$buffer = fgets($handle, 4096);
$existingText .= $buffer;
}// end while
//echo $existingText;
fclose($handle);
}// end if
$handle = fopen("blogfile.txt", "w");
$newStuff = "\n<div class=\"newEntry\">";
$newStuff .= "\n\t<div class=\"title\">" . $thisTitle . "</div>";
$newStuff .= "\n\t<div class=\"message\">" . $thisMessage . "</div>";
$newStuff .= "\n</div>";
$allStuff = $newStuff . $existingText;
fwrite($handle, $allStuff);
fclose($handle);
}// end writeToBlog
   ?>

It does not work, just something wrong here.

Parco Guan
  • 33
  • 1
  • 7
  • instead of that use json and store in server, json can be converted into array and back to json, its very handy instead of that text – Jerson Sep 27 '20 at 03:30
  • well, I need to WRITE and read from the text for some reason – Parco Guan Sep 27 '20 at 04:36
  • then your need to use [domdocument](https://www.php.net/manual/en/class.domdocument.php) to parse the written html which is considerably more convoluted then making some json and dynamically rendering the blog post from the json files (or do both) – Lawrence Cherone Sep 27 '20 at 04:44
  • also .txt wont render as html in browser – Lawrence Cherone Sep 27 '20 at 04:48
  • Try using `file_get_content()` and `file_put_content()`. See [this answer](https://stackoverflow.com/a/3332302/1685196) – Michel Sep 27 '20 at 11:15

0 Answers0