views:

172

answers:

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  A: 

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).

Tom Haigh
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.
coolboycsaba
`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: http://php.net/json_encode
artlung
+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.
bobince
A: 

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]); ?>;
artlung
Perhaps `rtrim()` would be more appropriate?
LeguRi
Sure, `rtrim()` http://php.net/rtrim would work too.
artlung
I think the rtrim() or the trim() will work. Thanks!
coolboycsaba
A: 

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

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