Chrysotribax
Chrysotribax

Reputation: 839

How convert new lines to actual \n when writing javascript array within php loop

I have a piece of code which writes a JS array of objects within the PHP code (retrieved from a mysql database) like this :

echo "var tab = [\n";
while($row = mysql_fetch_row($resultat)){
$numero = $row[0];
$notes = $row[1];
echo "{\n";
echo "numero:\"".$numero."\",";
echo "notes:\"".$notes."\" ";
echo "\n},";
}
echo "\n]";

(I simplified the code for the purposee... in the actual code the last comma is deleted)

The problem is : if I have new lines into $notes, it brakes the JS array and generates a JS parse error, since the new line is written as a real new line in the JS code, and not as "\n" as it should be.

For example, the text

"foo bar
foo bar"

Should be written in the JS array :

"foo bar\nfoo bar".

All I want to do is writing "\n" in place of actual new lines.

I tried this :

$notes = str_replace("\n", '\n', $row[1]);

But no success. Any idea ?

Upvotes: 0

Views: 189

Answers (2)

Ronni Egeriis Persson
Ronni Egeriis Persson

Reputation: 2289

The best way for you to convert your PHP array into JSON, is to use the json_encode function:

$rows = [];
while ($row = mysql_fetch_assoc($resultat)) {
    $rows[] = $row;
}
echo json_encode($rows);

I can't remember if there is an easier way to get the entire result set through the older mysql functions. I would recommend you to use PDO instead of mysql_query, mysql_fetch_row, etc.: http://www.php.net/manual/en/book.pdo.php

Edit:

If you want to assign the JSON object to a variable, e.g. inside a <script> block, do this:

<script>
var myArray = <?= json_encode($rows) ?>;
</script>

Upvotes: 2

Brad Faircloth
Brad Faircloth

Reputation: 327

I believe this would work if you escape out the slash in php, like this: \\n

I haven't tested this, but if I remember correctly this should work.

But, if all you are trying to do is display the text on an HTML page why not use a <br /> tag in place of \n that would give you an actual break where the \n would just start a new line in your code but just display as a space in the browser

Upvotes: 0

Related Questions