I have a script which creates an array containing entries for a table that I'd like to encode as json to send to my app. Each entry is an associative array of k/v pairs of string=>string|int. The code to generate the full array is as follows:
$entries = [];
foreach($stats as $i => $stat){
$playerStats = new Player_Stats($stat);
$entry = [
'place' => $i,
'name' => $playerStats->name(),
'elo' => $playerStats->currentRating(),
'highest' => $playerStats->highRating(),
'masterPoints' => $playerStats->onlineMasterPoints(),
'winLose' => $playerStats->matchesWonLost(),
'winRate' => $playerStats->winPercent(),
'numEvents' => $playerStats->numEvents(),
'wins' => $playerStats->eventsWon(),
'placed' => $playerStats->eventsPlaced()
];
$entries[] = $entry;
}
$result = json_encode($entries);
When I do a count or vardump etc on entries, It clearly shows that its been properly filled with the correct data. json_encode() returns false however. Using json_last_error_msg(), I get the UTF-8 error in the title: Malformed UTF-8 characters, possibly incorrectly encoded. All of the other posts on this issue I could find involved characters from other languages. All of the content in this array is made of the english alphabet and numbers, all ascii characters let alone utf-8.
Am I just missing something trivial (I usually am) or should I be looking for or trying something else completely?
-
can you provide us the payload for which you are getting error ?Al-Amin– Al-Amin2020年10月24日 17:40:30 +00:00Commented Oct 24, 2020 at 17:40
2 Answers 2
You could use the option to ignore these, JSON_INVALID_UTF8_IGNORE so your code would be json_encode($data, JSON_INVALID_UTF8_IGNORE);
This will ignore invalid UTF-8 as the name describes. You can see all options for json_encode here. https://www.php.net/manual/en/function.json-encode.php
2 Comments
ñSomething like this could do the trick:
$result = json_encode(array_map(utf8_encode, $entries))