How can i make sure a php to js string won't break
-
21-06-2021 - |
سؤال
I am writing a webpage that involves using a php array of strings to output a js array as follows
while($main2row = mysqli_fetch_assoc($result)) {
$tSummary[$main2row['id']] = '"'.$main2row['content'].'"';
$tTitle[$main2row['id']] = '"'.$main2row['title'].'"';
}
//the above gets the php from the sql database, then stores it in an array, both are string arrays
foreach ( $tSummary as $key => $val)
{
echo "summArray['".$key."'] = ".nl2br($val).";\n";
}
foreach ( $tTitle as $key => $val)
{
echo "titleArray['".$key."'] = ".nl2br($val).";\n";
}
//these foreach loops will print in a js script and will store the php arrays as js arrays
I know I should probably be using json but this is the way it was set up for me by someone else and I feel like I should adhere to their code.
The PROBLEM is that when the data is stored, it fails in the following way:
summArray['225594172793552897'] = " blah blah blah blah blah - blah.<br />
<br />
blah blah blah blah....."; /* this one is messed up */
summArray['225595300046307328'] = "text text text text text text text text text text text text text text ."; /* this one is fine */
I notice that the string breaks wherever there is a line break so i tried to use nl2br but, while that added a br tag, it did not remove the line break. is there any way I can get rid of this line break?
المحلول
Instead of nl2br($val)
, try str_replace("\n", "\\n", $val)
to get newlines in JavaScript, or str_replace("\n", "\\n", nl2br($val))
to get HTML linebreaks as well.
لا تنتمي إلى StackOverflow