The manual for json_encode specifies this:

All string data must be UTF-8 encoded.

Thus, try array_mapping utf8_encode() to your array before you encode it:

Copy$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);

// {"funds":"ComStage STOXX\u00c2\u00aeEurope 600 Techn NR ETF"}

For reference, take a look at the differences between the three examples on this fiddle. The first doesn't use character encoding, the second uses htmlentities and the third uses utf8_encode - they all return different results.

For consistency, you should use utf8_encode().

Docs

  • json_encode()
  • utf8_encode()
  • array_map()
Answer from scrowler on Stack Overflow
🌐
PHP
php.net › manual › en › function.json-encode.php
PHP: json_encode - Manual
After unserializing them and sending them through the json_encode function the numeric values in the original array were now being treated as strings and showing up with double quotes around them. The fix: Prior to encoding the array, send it to a function which checks for numeric types and casts accordingly. Encoding from then on worked as expected. ... Solution for UTF-8 Special Chars.
🌐
SitePoint
sitepoint.com › php
PHP, json_encode and special characters?!?! - PHP - SitePoint Forums | Web Development & Design Community
September 21, 2009 - I’m trying to figure this out… $users = array('Peter Jørgensen', 'Glen Thompson', 'Kit Anderson'); $checkuser = array(); foreach ($users as $user){ $checkuser[] = array($user); } echo json_encode($checkuser) ; This prints out: [[“Peter J\u00f8rgensen”],[“Glen Thompson”],[“Kit Anderson”]] As you can see the “Jørgensen” comes out like “J\u00f8rgensen”… How do I get it to show/print this correct???
🌐
Experts Exchange
experts-exchange.com › questions › 28628085 › json-encode-fails-with-special-characters.html
Solved: json_encode fails with special characters | Experts Exchange
March 3, 2015 - The article has cut-and-paste code examples. http://www.slideshare.net/RayPaseur/unicode-php-and-character-set-collisions · Get a FREE t-shirt when you ask your first question. We believe in human intelligence. Our moderation policy strictly prohibits the use of LLM content in our Q&A threads. ... Dumping the array, json etc.. :) var_dump($rows); $json = json_encode($rows); var_dump($json);
🌐
Pontikis
pontikis.net › blog › how-to-escape-json-special-characters-using-php
How to Escape JSON Special Characters using PHP - pontikis.net
July 6, 2024 - 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.
Top answer
1 of 3
17

You are having error because of new line in your string

$string = '{"projectnumber" : "4444","projecdescription" : "4444", "articles" : [{"position":1, "article_id" : 676, "online_text" : "### Behälter; Band I-III nach indiv. Stückliste, Sprache: DE 
 - Sprache: de"},{"position":2, "article_id" : 681, "online_text" : "### Behälter; Band I-III nach indiv. Stückliste, Sprache: ### 
 - Sprache: en"}]}';


$string = preg_replace("/[\r\n]+/", " ", $string);
$json = utf8_encode($string);
$json = json_decode($json);
var_dump($json);

Output

object(stdClass)[1]
  public 'projectnumber' => string '4444' (length=4)
  public 'projecdescription' => string '4444' (length=4)
  public 'articles' => 
    array
      0 => 
        object(stdClass)[2]
          public 'position' => int 1
          public 'article_id' => int 676
          public 'online_text' => string '### Behälter; Band I-III nach indiv. Stückliste, Sprache: DE   - Sprache: de' (length=78)
      1 => 
        object(stdClass)[3]
          public 'position' => int 2
          public 'article_id' => int 681
          public 'online_text' => string '### Behälter; Band I-III nach indiv. Stückliste, Sprache: ###   - Sprache: en' (length=79)
2 of 3
13

Voting for the newline too

json_decode_nice + keep linebreaks:

function json_decode_nice($json, $assoc = TRUE){
    $json = str_replace("\n","\\n",$json);
    $json = str_replace("\r","",$json);
    $json = preg_replace('/([{,]+)(\s*)([^"]+?)\s*:/','3":',$json);
    $json = preg_replace('/(,)\s*}$/','}',$json);
    return json_decode($json,$assoc);
}

If you want to keep the linebreaks just escape the slash.

You don't need utf-8 encode, if everything is set to utf-8 (header, db connection, etc)

🌐
Texelate
texelate.co.uk › blog › cleaner-json-encoding-with-php
Cleaner JSON encoding with PHP | Texelate
PHP_EOL; // Notice the £ sign is shown as is echo json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL . PHP_EOL; // Forward slashes are no longer escaped echo json_encode($array, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT); // Now it's multiline and indented properly /** Outputs: {"foo":"I paid \u00a3100 for the computer\/laptop"} {"foo":"I paid £100 for the computer\/laptop"} {"foo":"I paid £100 for the computer/laptop"} { "foo": "I paid £100 for the computer/laptop" } */ ?></pre>
🌐
SSOJet
ssojet.com › escaping › json-escaping-in-php
JSON Escaping in PHP | Escaping Techniques in Programming
These include double quotes ("), backslashes (\), and control characters like newlines (\n) or tabs (\t). PHP's json_encode() function handles this automatically, transforming these special characters into their escaped representations (e.g., ...
Find elsewhere
🌐
Reddit
reddit.com › r/phphelp › php is adding escape characters to my json string and i have no idea why,
r/PHPhelp on Reddit: PHP is adding escape characters to my JSON string and I have no idea why,
April 18, 2023 -

I have a website that lets the user build a dynamic form (think tabs with widgets) and then reduce the whole thing to a string with json.stringify().

But when I pass it to PHP (on one of our two systems to make things weirder) it adds a mess of escape characters. For example:

  {\\"tab_type\\":\\"accordion\\",\\"options\\"{\\"tab::style\\":\\"color:0x8000ff00\\",  

When the correct formatting should look like:

 "type":"accordion","options":{"tab::style":"color:0x8000ff00" 

The json is stringified properly on the JS side but it adds the slashes as soon as I look at the variable in the GET/POST on the PHP side.

🌐
IT Blog
blog.hostlike.com › home › technology › program language › php › escape json special characters using php
Escape JSON Special Characters using PHP - IT Blog
May 22, 2018 - use the json_encode constant JSON_HEX_APOS as the second parameter which will convert all single quotes ' to \u0027. : var t = <?php echo json_encode($data,JSON_HEX_APOS);?>;
🌐
GitHub
github.com › jmathai › epiphany › issues › 77
Returning json with special characters doesn't work · Issue #77 · jmathai/epiphany
February 26, 2013 - Hi guys! I'm trying to return some strings with special characters but always my json returns with null values instead the correct string. Am I doing something wrong or is it a bug? I tried test the example too and always the value is nu...
Author   evandrowcg
🌐
Stack Overflow
stackoverflow.com › questions › 40098830 › special-characters-and-json-encode
php - Special characters and json_encode - Stack Overflow
Check your PHP File Encoding and it should be UTF-8. Use PHP header(header('Content-Type: text/html; charset=utf-8');) or meta tag (<meta http-equiv="Content-type" content="text/html; charset=utf-8" />) to allow the file to handle UTF8 char. Run SET NAMES 'utf8' sql before fetching the information. Then use array_map and json_encode function.
🌐
Stack Overflow
stackoverflow.com › questions › 15156319 › json-encode-doesnt-take-care-of-special-characters
php - JSON_encode doesn't take care of special characters? - Stack Overflow
But it is only a list of characters, every time I get a new special character I have to manually deal with it and add it to the character and its replacement list. ... if the string is utf-8 json_encode does correctly handle special characters, so does json_decode, usually there is no extra replacement required if u are working with valid json, post your json code please!
🌐
Google Groups
groups.google.com › g › jstree › c › Ir7g0AY4KQI
Special characters with JSON
I'm dealing with filenames: PHP lists files, converts to JSON which will end up in a jsTree. In german there are a lot of "umlauts" like ä ö ü... Because of them i need to convert between UTF-8 and ISO. - Data received from jsTree (creating, renaming, moving files/folders) needs to convert from UTF-8 using decode_utf8(). - Data sending from PHP to jsTree needs to be converted using encode_utf8() And: make sure PHP sends a header identify the data as UTF-8 using: header('Content-Type: text/html; charset=utf8'); A bit tricky sometimes, but works for me.