PHP: literal \n rather than new line
I have a php var which, when echoed, writes a JS function into the source of a page. The function loops through a CSV and so it has the following line within it:
$str="var lines = data.split('\n'开发者_开发技巧);";
At the present time, when echoed, I get this 'correct' JS written into the source:
var lines = data.split('
');
Instead, I want to echo the literal string \n
into the source of the page.
Can anyone point me in the right direction? Thanks.
Escape the slash.
"\\n"
So that it is treated as a slash instead of an escape character.
Try this:
$str="var lines = data.split('\\n');";
you can escape \
like this: \\
.
But I would put the whole JS functionality into a .js file, include that from the generated HTML, and call the specific function when needed. And generate a minimalistic js code, like var config = {....}
if I have to communicate some page related information.
You almost never need dynamically generated JS code. It's a lot harder to read and you're wasting CPU and network bandwidth...
Either the solutions in the earlier answers, or invert the quotes by using single quotes as the PHP string delimiter:
$str='var lines = data.split("\n");';
Or escape the inner quotes, if you want to keep single quotes for javascript as well when using single quotes as the PHP string delimiter.
$str='var lines = data.split(\'\n\');';
See the docs on quoted strings in PHP as well about how single quoted strings and double quoted strings behave differently.
精彩评论