NullHypothesis
NullHypothesis

Reputation: 4506

json_encode issues with utf-8 and unicode

I'm having some issues and wanted to ask for some help.

Some of my content editors will add characters which I believe are considered unicode characters. One char is the ellipsis three dots which take up one space instead of the traditional ... (counts as 3 chars). The other is the apostrophe ’ instead of ' which also screws with me.

Here is the rough code i'm doing:

//Retrieve a list of content items. Each content item is an array, and all of the content items are inside their own array.
$myArray = _contentService->GetContentArray(); 

//so now $myArray is a two-dimensional array          

//One record inside the above array contains a key called 'description' whose value contains the ellipsis

die(json_encode($myArray, JSON_UNESCAPED_UNICODE ));

this produces nothing (screen is white).

die(json_encode($myArray)); //also produces a white screen.

So the end result is I'm trying to run json_encode over a two-dimensional array. When the description column of each array in the array is comprised of non-unicode chars, it works fine and outputs my JSON array.

When ellipsis or ’ is used, the whole screen turns white and nothing outputs.

The manual says you need to use UTF-8 encoding only for json_encode, however it also says higher versions support JSON_UNESCAPED_UNICODE, however would't this simply escape my ellipsis as like \uxxxx instead? Is there a way to actually preserve the ellipsis?

I tried several recommendations from StackOverflow but i'm getting nothing in all cases. The minute I remove the ellipsis it works fine.

Is my thinking correct in that the ... is throwing off everything because it's unicode?

Thank you so much!

Upvotes: 1

Views: 628

Answers (1)

Kaylined
Kaylined

Reputation: 665

It's a bit of an ugly solution, but it should work; you can just format and output the array manually as JSON, instead of encoding it with the PHP function.

echo '{';
foreach($myArray as $key => $value){
  if(is_array($value)){
    echo '"'.$key.'": [';
    foreach($value as $k => $v){
      echo '"'.$k.'":"'.$v.'",' . PHP_EOL;
    }
    echo ']';
  }else{
    echo '"'.$key.'":"'.$value.'",' . PHP_EOL;
  }
}
echo '}';

Should just output it as is, structured as JSON. Whatever is processing this JSON at the end, may have to deal with the encoding issues afterwards, but this should deliver it properly.

It's just an example, you may need to rework it(probably make it a function, and iterate through that) to fit your exact needs.

Upvotes: 1

Related Questions