3

I have a txt file on the server which contains 10 lines of text. The text file is rewritten sometimes, and I get new lines using "\r\n". My problem shows when I want to load the lines in javascript variables. I do it like this, but this work only for numbers or for the last line of the file, because its not using the breakline tag: var x = '<?php echo $file[0]; ?>'; Ive tried to alert(x) but it`s not working.... (working only if I read the last line) Any idead ?

3 Answers 3

3

I'm not sure I completely understand the question, but you should be able to use json_encode() which will escape the data appropriately:

var x = <?php echo json_encode($file[0], JSON_HEX_TAG); ?>;

As others have said, you can trim() the data to remove trailing whitespace/line breaks. You should still use json_encode() in addition to this as otherwise it will still be possible to break out of the javascript string (e.g. by sending a string with a quote in).

Sign up to request clarification or add additional context in comments.

3 Comments

But json_encode() is not for outputting an entire array ? My problem is that I want to cut out that "\r\n" breakline tag from the end of the text, the breakline is invisible, but it affects the work of my script.
json_encode() can turn basically any PHP variable into a "JavaScript-safe" representation. It won't delete your newline, rather it will safely encode them. More info: php.net/json_encode
+1 much better than trying to work out JavaScript escaping yourself. Ideally, use the JSON_HEX_TAG flag to ensure that a </script> in the content doesn't cause the surrounding script block to end early.
0

You want trim():

var x = '<?php echo trim($file[0]); ?>';

But if you read the file(), you could array_map() it with trim() and then keep doing what you're doing:

$values = array_map("trim", file('input-file.txt'));

You might consider what happens if someone decides to include a single quote in the variable with this approach.

EDIT: Then you can add json_encode() as suggested in other answers:

var x = <?php echo json_encode($file[0]); ?>;

1 Comment

Perhaps rtrim() would be more appropriate?
0

Thanks for all! The I solved the problem with the help of artlung and Richard JP Le Guen:

var x = <?php rtrim($file[0]); ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.