How to save a text string with line breaks to a My

2019-02-25 03:55发布

问题:

In SugarCRM I have a Textarea field that I am trying to save data to with line breaks.

IF I insert <br> tags, then they show up as text break tags. If I try something like \n then it also shows up as text.

Now if I go into SugarCRM and edit a record, I can type in text and make a linebreak. Save the record and view it again and the line breaks show up as I would want them to!

I am trying to save data with line breaks to the same field from a remote API script.

I went into the Database with phpMyAdmin to see how the field looked and here it is...

The first 3 lines have proper line breaks which I made inside SugarCRM editing a record manually.

The line after are from my remote API script where I had saved <br> tags into the string.

Line 1 Text: ghfghdf
Line 1 Color: #0064FF
Line 1 Font: Architect
Line 2 Text: fghfg<br /> Line 2 Color: #9F00FF<br /> Line 2 Font: Belshaw<br /> Line 3 Text: fghdhdhdf<br /> Line 3 Color: #FF5000<br /> Line 3 Font: Benguiat<br />

Any ideas how I can make my PHP code save a string to this field and have line breaks when viewing it in the database just like the first 3 lines above are?

回答1:

As suggested in comments, this kind of issue tends to be related to the fact that in single quoted strings :

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash, double it (\\).

All other instances of backslash will be treated as a literal backslash: this means that the other escape sequences you might be used to, such as \r or \n, will be output literally as specified rather than having any special meaning.

but in double quoted strings :

PHP will interpret more escape sequences for special characters

sequence : \n then having the meaning of linefeed (LF or 0x0A (10) in ASCII)

So echo '\n' will print \n while echo "\n" will allow you to have a new line as excepted.

And of course, you also can use PHP_EOL to make it cross OS.



回答2:

When attempting to store data that has line breaks, you want to use the nl2br() function inside of php before you store the data. I had the same issues before and after months and months of trying different things to get it to work right on a client's site, it was on SO that I found the answer one day.

The key is to convert the data by using nl2br() before you store it.

Hope this helps.



回答3:

Use PHP_EOL instead of <br/> or \n

e.g.

$array = array("a","b");
$string = implode(PHP_EOL , $array);