loading a text file from php into a web page

Ask about general coding issues or problems here.

Moderators: egami, macek, gesf

Post Reply
New php-forum User
New php-forum User
Posts: 1
Joined: Mon Jan 20, 2020 11:42 am

Mon Jan 20, 2020 12:00 pm

I am trying to load texts in my webpage (test.php) from a text file, adding this php snippet at the very top

$TOTAL_TEXT = file_get_contents('./consultoria.txt');
Down the page, in the <script> section, I am trying to pass the $TOTAL_TEXT string to a js variable

$(document).ready(function() {
var out = "<?php echo"$TOTAL_TEXT"?>";
alert ('out is ' + out );

But it crashes because of Uncaught SyntaxError: Invalid or unexpected token

On the other hand, if the $TOTAL_TEXT variable is set to "HELLO" (instead of read a text file),... the out variable gets properly loaded and shown in the alert...

Why this difference in behaviour? I am absolutely novice at php and js, anyway

User avatar
php-forum GURU
php-forum GURU
Posts: 929
Joined: Mon Feb 22, 2016 5:52 pm

Mon Jan 20, 2020 1:27 pm

It depends on what is in the test.php file, if it has quotation marks or php variables, it might screw up the JavaScript, have a look at the error console for errors.

You don't need to use quotation marks in PHP when using echo:

Code: Select all

is fine since you are not outputting literals, also note that you didn't use a closing semi colon in your PHP.

For instance if your file is something like this:

Code: Select all

Welcome to "My" file
The quotation marks around 'My' will try to close and open your JavaScript variable declaration.

Code: Select all

var out = "Welcome to "My" file";
There's no point in using include when you're converting it to use as a JavaScript variable, it's a waste of CPU time at both ends, if you intend to do some processing to the file for output, do it in PHP.

Since JavaScript relies on permission on the users browser, it's wise to only use JavaScript to do things to enhance a pages usefulness, but it shouldn't restrict any users from using your web site; in other words, learn HTML, CSS then PHP (in that order) first, before even thinking of using JavaScript.
Post Reply