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 fo开发者_如何转开发r numbers or for the last line of the file, because its not using the breakline tag: var x = '<?php echo $file[0]; ?>';
I
ve tried to alert(x) but it`s not working.... (working only if I read the last line)
Any idead ?
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).
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]); ?>;
Thanks for all! The I solved the problem with the help of artlung and Richard JP Le Guen:
var x = <?php rtrim($file[0]); ?>
精彩评论