PHP WordPress wp_remote_get when hitting a 3rd party REST API returns content-type windows-1252, but I need utf-8

I’m calling a REST API, but they’re returning items with content-type ‘windows-1252’, yuck.
Result was either ? marks all over, or /’/g
Here’s an example sentence returned:

//Young Life/’/gs Washington Family Ranch, nestled in a high desert valley in Central Oregon, seeks to…

The key is getting the correct order of parameters, and the correct content-type you’re receiving, and the one you’d like instead:
mb_convert_encoding($mixed, ‘utf-8’, ‘windows-1252’)

This goes FROM windows-1252 TO utf-8

And it still leaves a few items, namely curly brackets “’” still, so a string_replace is still required after the conversion.

Additionally, the endpoint returns… an object? an array? one inside the other? ug, so this calls itself recursively until it’s handled.
Just pass in the whole thing, whatever it is, returned:
$searchResult = utf8ize($searchResult);
Nice.

This was a super hassle to figure out, so I’m saving the reminder here. Hope it helps someone.

function utf8ize( $mixed ) {
if (is_object($mixed)) {
foreach ($mixed as $key => $value){
$mixed->$key = utf8ize($value);
}
}
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
}
if (is_string($mixed)) {
//return mb_convert_encoding($mixed, “UTF-8”);
$mixed = str_replace(“’”, “‘”, mb_convert_encoding($mixed, ‘utf-8’, ‘windows-1252’));
}
return $mixed;
}

Leave a Reply

You must be logged in to post a comment.