I made a rudimentary label-printing web app using PHP, and I need a way to store the templates. These consist of a few small text entries and some number and boolean values. Normally I would just use JSON but the text values contain line breaks which JSON can't handle. XML is a pain because there is HTML markup I would have to escape. Is there another alternative format I could use to store this information which is human-readable?
Asked
Active
Viewed 320 times
0
-
3you should look at http://stackoverflow.com/questions/4253367/how-to-escape-a-json-string-containing-newline-characters-using-javascript – falinsky Mar 14 '14 at 01:44
-
I think he wants to encode in PHP and then send to the client if I am reading correctly. The referenced article describes how to encode a string for JSON in Javascript. – David H. Bennett Mar 14 '14 at 02:01
-
I'm actually just trying to save the file on the server and then retrieve it later. Nothing is being sent to the client for Javascript. – JaredL Mar 14 '14 at 03:43
-
It's not true that JSON can't handle line breaks. You just need to escape them as `\n`. – Michael Kay Mar 14 '14 at 09:08
1 Answers
0
I assume you want to prep the data and encode it into JSON on the server then send it to the client. This article gives a good explanation on how to prep your data escaping the proper values for evaluation on the client.
Newer versions of PHP (> 5.2) have the json_encode() function which will perform this task:
$str_valid=json_encode($str);
There are many options for this function, read the docs for more info.
Older versions of PHP need to provide this functionality:
/**
* @param $value
* @return mixed
*/
function escapeJsonString($value) { # list from www.json.org: (\b backspace, \f formfeed)
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
Interestingly, the article references back to this StackOverflow post where the same function appears.

Community
- 1
- 1

David H. Bennett
- 1,822
- 13
- 16
-
Don't try to manipulate strings as if they are json. You can, but it's more trouble than it's worth. Create the object with keys and values, then call json_encode on the object itself to get the json string. The json plugin guys have already done all the work for you, plus they keep it maintained. – Chris Strickland Jul 26 '22 at 00:46