'echo multiline from sqlite in php
How can I echo (PHP) a multiline text value from SQLITE3 directly into HTML?
In PHP, I query a SQLITE database, and get a multiline string as the value. However, I can't find out how to echo the string as multiple lines within html.
I know that the string is a multiline string because if I echo it between <pre> tags, it shows as multiline. I can also var_dump() between <pre> tags and it shows as a multiline string. However, I don't want to echo it between <pre> tags because this clears other formatting that would usually be applied by CSS: color, font, size etc.
Let's say that my SQLite value is:
$sql['multiline'] = "This is
a multiline
string";
A quick test of this:
1 // pdo sql query up here
2 $note = $sql['multiline'];
3 echo "<pre>";
4 var_dump($note);
5 echo "</pre>";
Results in:
string(30) "This is
a multiline
string
"
(note: the length of the string is always longer then actual quantity of characters - plus 2 for each new line - can I preg_replace using \n or anything?)
I've been trying HEREDOC and NOWDOC in PHP to echo out the multiline string correctly as multiple lines. But this doesn't seem to work:
1 // pdo sql query up here
2 $note = <<<HEREDOC
3 $sql['multiline']
4 HEREDOC;
echo $note;
Results in:
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting '-' or identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in /exampledir/file.php on line 3
Below doesn't get errors, but still prints the multiline string on a single line:
1 // pdo sql query up here
2 $text = $sql['multiline'];
3 $note = <<<HEREDOC
4 $text
5 HEREDOC;
echo $note;
Results in:
This is a multiline string
Some thoughts:
- Should I be formatting the value differently before inserting it to SQLite?
- Should I echo each new line between
<p>tags using foreach? - Should I be trying to format the value using HTML tags or CSS rather then PHP? I'm not aware of anything relevant for this?
- Just not sure of the standard way to approach this.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
