Php escape json string

Predefined Constants

The constants below are defined by this extension, and will only be available when the extension has either been compiled into PHP or dynamically loaded at runtime.

The following constants indicate the type of error returned by json_last_error() or stored as the code of a JsonException .

JSON_ERROR_NONE ( int ) No error has occurred. JSON_ERROR_DEPTH ( int ) The maximum stack depth has been exceeded. JSON_ERROR_STATE_MISMATCH ( int ) Occurs with underflow or with the modes mismatch. JSON_ERROR_CTRL_CHAR ( int ) Control character error, possibly incorrectly encoded. JSON_ERROR_SYNTAX ( int ) Syntax error. JSON_ERROR_UTF8 ( int ) Malformed UTF-8 characters, possibly incorrectly encoded. JSON_ERROR_RECURSION ( int ) The object or array passed to json_encode() include recursive references and cannot be encoded. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, null will be encoded in the place of the recursive reference. JSON_ERROR_INF_OR_NAN ( int ) The value passed to json_encode() includes either NAN or INF . If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, 0 will be encoded in the place of these special numbers. JSON_ERROR_UNSUPPORTED_TYPE ( int ) A value of an unsupported type was given to json_encode() , such as a resource. If the JSON_PARTIAL_OUTPUT_ON_ERROR option was given, null will be encoded in the place of the unsupported value. JSON_ERROR_INVALID_PROPERTY_NAME ( int ) A key starting with \u0000 character was in the string passed to json_decode() when decoding a JSON object into a PHP object. JSON_ERROR_UTF16 ( int ) Single unpaired UTF-16 surrogate in unicode escape contained in the JSON string passed to json_decode() .

The following constants can be combined to form options for json_decode() .

JSON_BIGINT_AS_STRING ( int ) Decodes large integers as their original string value. JSON_OBJECT_AS_ARRAY ( int ) Decodes JSON objects as PHP array. This option can be added automatically by calling json_decode() with the second parameter equal to true .

The following constants can be combined to form options for json_encode() .

JSON_HEX_TAG ( int ) All < and >are converted to \u003C and \u003E. JSON_HEX_AMP ( int ) All & are converted to \u0026. JSON_HEX_APOS ( int ) All ‘ are converted to \u0027. JSON_HEX_QUOT ( int ) All » are converted to \u0022. JSON_FORCE_OBJECT ( int ) Outputs an object rather than an array when a non-associative array is used. Especially useful when the recipient of the output is expecting an object and the array is empty. JSON_NUMERIC_CHECK ( int ) Encodes numeric strings as numbers. JSON_PRETTY_PRINT ( int ) Use whitespace in returned data to format it. JSON_UNESCAPED_SLASHES ( int ) Don’t escape / . JSON_UNESCAPED_UNICODE ( int ) Encode multibyte Unicode characters literally (default is to escape as \uXXXX). JSON_PARTIAL_OUTPUT_ON_ERROR ( int ) Substitute some unencodable values instead of failing. JSON_PRESERVE_ZERO_FRACTION ( int ) Ensures that float values are always encoded as a float value. JSON_UNESCAPED_LINE_TERMINATORS ( int ) The line terminators are kept unescaped when JSON_UNESCAPED_UNICODE is supplied. It uses the same behaviour as it was before PHP 7.1 without this constant. Available as of PHP 7.1.0.

Читайте также:  Joomla index php view

The following constants can be combined to form options for json_decode() and json_encode() .

JSON_INVALID_UTF8_IGNORE ( int ) Ignore invalid UTF-8 characters. Available as of PHP 7.2.0. JSON_INVALID_UTF8_SUBSTITUTE ( int ) Convert invalid UTF-8 characters to \0xfffd (Unicode Character ‘REPLACEMENT CHARACTER’) Available as of PHP 7.2.0. JSON_THROW_ON_ERROR ( int ) Throws JsonException if an error occurs instead of setting the global error state that is retrieved with json_last_error() and json_last_error_msg() . JSON_PARTIAL_OUTPUT_ON_ERROR takes precedence over JSON_THROW_ON_ERROR . Available as of PHP 7.3.0.

Источник

How to Escape JSON Special Characters using PHP

You are currently viewing How to Escape JSON Special Characters using PHP

JSON is a data format (possible the most) suitable for use with javascript, especially on ajax operations.

Some characters in strings have to be escaped, otherwise json cannot be parsed and an error will occur.

These characters are double quotes (“), backslash (\) and control characters (most inportant in common use is new line character). You don’t have to escape single quotes. For details, see here.

For example: the following string is invalid:

$str='Lorem ipsum "dolor" sit amet, consectetur \ adipiscing elit.';
$str="Lorem ipsum \"dolor\" sit amet,\nconsectetur \\ adipiscing elit.";

How?

The ideal way to escape a string with php, before create a json string is json_encode. This requires php > 5.2

(remark: json_encode will enclose initial string with double quotes)

php versions older that 5.2

As an alternative (for older versions of php), a function like the following (Source: stackoverflow) could be used:

/** * @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; >

Entrepreneur | Full-stack developer | Founder of MediSign Ltd. I have over 15 years of professional experience designing and developing web applications. I am also very experienced in managing (web) projects.

Please Share This Share this content

Categories

Archives

NewsLetter

Ad - SiteGround Web Hosting - Crafted for easy site management. Amazing Speed; Powerful Tools; Top-rated support. Learn more.

LIKE OUR PAGE!

Say Hello to Gutenberg with my new Free WordPress Plugin Boilerplate for Developers!

Star it on Github!

  • Opens in a new tab
  • Opens in a new tab
  • Opens in a new tab
  • Opens in a new tab
  • Opens in a new tab
  • Opens in a new tab
  • Opens in a new tab

We are using cookies to give you the best experience on our website.

You can find out more about which cookies we are using or switch them off in settings .

Please select before continuing.

pontikis.net Logo

  • Privacy Overview
  • Strictly Necessary Cookies
  • 3rd Party Cookies
  • Cookie Policy

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Читайте также:  Php установить значение переменной

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

We use Google Analytics to collect statistics about our visitors.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

This website uses Google Adsense to display ads.

Keeping this cookie enabled helps us to improve our website.

Please enable Strictly Necessary Cookies first so that we can save your preferences!

More information about our Cookie Policy

We use Google Analytics to collect statistics about our visitors. Learn more about this provider

Cookie Domain Description Duration Type
_ga .pontikis.net The _ga cookie, installed by Google Analytics, calculates visitor, session and campaign data and also keeps track of site usage for the site’s analytics report. The cookie stores information anonymously and assigns a randomly generated number to recognize unique visitors. 2 years Analytics
_gid .pontikis.net Installed by Google Analytics, _gid cookie stores information on how visitors use a website, while also creating an analytics report of the website’s performance. Some of the data that are collected include the number of visitors, their source, and the pages they visit anonymously. 1 day Analytics
_gat_gtag_UA_334875_9 .pontikis.net Set by Google to distinguish users. 1 minute Analytics

Источник

Php Json String, Escape Double Quotes for Js Output

json_encode already takes care of this, you are breaking the result by calling stripslashes :

echo json_encode($data); //properly formed json

PHP JSON String escape Double Quotes inside value?

Since yesterday I was trying to solve this tricky problem, and after a lot of hair pulling I came up with this solution.

First let us clarify our assumptions.

  • json string should be right formated.
  • The keys and values are quoted with double quotation.

Analyzing the problem:

We know that json keys formated like this (,»keyString»:) and json value is (:»valueString»,)

keyString: is any sequence of characters except (:»).

valueString: is any sequence of characters except («,).

Our goal is to escape quotations inside valueString, to achive that we need to separate keyStrings and valueStrings.

  • But we have also a valid json format like this («keyString»:digit,) this will cause a problem because it breaks out assumption that says values always ended with («,)
  • Another problem is having empty values like («keyString»:» «)

Now after analyzing the problem we can say

  1. json keyString has (,») before it and («:) after it.
  2. json valueString can have (:») before and («,) after OR
    (:) before and digit as a value then (,) after OR
    (:) followed by (» «) then (,)
Читайте также:  Exe files java eclipse

The solution:
Using this facts the code will be

function escapeJsonValues($json_str) $patern = '~(. \s*"((. (?!"\s*:))+.)"\s*(?=\:))(?:\:\s*(?:(\d+)|("\s*")|(?:"((?!\s*")(. (?!"\s*,))+.)")))~'; 
//remove < >
$json_str = rtrim(trim(trim($json_str),'<'),'>');
if(strlen($json_str) <5) //not valid json string;
return null;
>
//put , at the start nad the end of the string
$json_str = ($json_str[strlen($json_str)-1] ===',') ?','.$json_str :','.$json_str.',';
//strip all new lines from the string
$json_str=preg_replace('~[\r\n\t]~','',$json_str);

preg_match_all($patern, $json_str, $matches);
$json=' for($i=0;$i$json.='"'.$matches[1][$i].'":';
//value is digit
if(strlen($matches[2][$i])>0) $json.=$matches[2][$i].',';
>
//no value
elseif (strlen($matches[3][$i])>0) $json.='"",';
>
//text, and now we can see if there is quotations it will be related to the text not json
//so we can add slashes safely
//also foreword slashes should be escaped
else $json.='"'.str_replace(['\\','"' ],['/','\"'],$matches[4][$i]).'",';
>
>
return trim(rtrim($json,','),',').'>';
>

Note: The code realizes white spaces.

Will php’s json_encode() always use double quotes as string delimiter?

Yes, as defined in the JSON spec, the delimiter will always be » . However, values may contain ‘ characters, which would break your HTML. To keep it simple and not worry about what might or mightn’t pose an issue, HTML-escape your values!

This is guaranteed to work, always, no matter what values you pipe in or how you encode them.

NOTE that htmlspecialchars will by default only encode » , not ‘ ; so you must use » as the delimiter in HTML (or change the default escaping behavior).

How to escape double quotes in JSON

"maingame": "day1": "text1": "Tag 1", 
"text2": "Heute startet unsere Rundreise \" Example text\". Jeden Tag wird ein neues Reiseziel angesteuert bis wir. "
>
>

(just one backslash ( \ ) in front of quotes).

Escaping quotes in a javascript object generated from PHP

My attempts to edit @kmoser’s answer with the actual solution that worked were rejected in peer review, so here’s what worked. All credit to @kmoser:

$json_feedback = preg_replace( preg_quote(‘/\u/’), ‘\\\\\\\\u’, json_encode( $feedback, JSON_HEX_APOS | JSON_HEX_QUOT ) );

It works by replacing singles and double quotes with hex strings when the data is retrieved from the MySQL database. For reasons I don’t understand, that still broke the javascript, so I then did a preg_replace to put an additional backslash before the escaped code.

Notice how many backslashes I had to put in to persuade the preg_replace to put in the additional backslash to prevent the javascript breaking. I may be able to get away with fewer backslashes, the number that appears here is mostly out of sheer frustration with this silly issue!

Replace double quotes with single quotes in json string in php

I hope this works as expected ([^<,:])"(?![>,:])

$json='Description">';
$json=preg_replace('/([^<,:])"(?![>,:])/', "$1".'\''."$2",$json);

PHP Add double quotes before and after variable in json string

OK, if you’re new to all this, maybe regular expressions aren’t the best answer.

You can also use a simple str_replace function (doc) like this :

str_replace(array(‘file:’, ‘label:’),array(‘»file»:’, ‘»label»:’),$your_json_string);

To exploit the json in php, you’ll need to decode it using json_decode , and use a loop to check the label values (I advise a foreach loop).

Источник

Оцените статью