0

I am writing some PHP code to display text from data.txt to the website. My code is:

<!DOCTYPE html>
<html lang="en" dir="ltr">

  <head>
    <link rel="stylesheet" href="style.css">
    <meta charset="utf-8">
  </head>
  <body>
    <?php
      //loading data
      $file = fopen("data.txt", "r") or die("unable to open!");
      $data = fread($file, filesize("data.txt"));
      echo "<p>" . $data . "</p>";
    ?>
  </body>
</html>

The output I'm getting is quite weird:

" . $data . "

"; ?> 

The things that are wrong are:

  1. the variable is formatted incorrectly

  2. echo outputs everything but the HTML tags in the PHP script after it, although I ended it with a semicolon.

It is probably some stupid mistake, but what am I doing wrong?

Also, my data.txt isn't empty.

SonicAsF
  • 17
  • 7
  • 1
    Looks like it's outputting the actual PHP code instead of executing it. What's the file extension on the file? `.php` or `.html`? Are you running the page through a web server (going to something like: `http://localhost/...` or similar) or do you double click on the file top open it in the browser? Do you have a web server installed? Which? What OS? – M. Eriksson Dec 22 '19 at 15:38
  • @MagnusEriksson Yes, that is the problem. My file extension is .php, and I'm double-clicking the file to open it up. I'm using Windows. I do not have any web servers installed. – SonicAsF Dec 22 '19 at 15:39
  • 2
    You can't execute PHP files like that. You need to run the script through a web server before it reaches the client (browser). The web server tells the PHP interpreter to execute the code and then returns the result to the browser. Browsers can't execute PHP (PHP is server side and the browser only handles client side, like JS, HTML and CSS). So you're currently skipping the part where the web server executes the PHP code. Do some research into setting up a full development environment for building web apps with PHP. – M. Eriksson Dec 22 '19 at 15:44
  • Use XAMPP for test your code. – Simone Rossaini Dec 22 '19 at 17:40

0 Answers0