Eddie
Eddie

Reputation: 26844

json_encode array with special character

I have this array

array (size=3)
  0 => 
    array (size=4)
      'lat' => string 'qqq' (length=11)
      'lng' => string 'qqq' (length=11)
      'housenumber' => string 'xxx' (length=3)
      'street' => string 'José Ellauri' (length=12)
  1 => 
    array (size=4)
      'lat' => string 'qqq' (length=11)
      'lng' => string 'qqq' (length=11)
      'housenumber' => string 'xxx' (length=4)
      'street' => string 'Francisco Solano García' (length=23)
  2 => 
    array (size=4)
      'lat' => string 'qqq' (length=11)
      'lng' => string 'qqq' (length=11)
      'housenumber' => string 'xxx' (length=3)
      'street' => string 'Ingeniero Carlos María Maggiolo' (length=31)

I am trying to json_encode that array but since there are special characters, i found out that i need to $toReturn = array_map('utf8_encode', $toReturn); But I'm getting an error. My code below.

$toReturn = array_map('utf8_encode', $toReturn);
echo json_encode($toReturn);

Im getting this error in my page.

( ! ) Warning: utf8_encode() expects parameter 1 to be string, array given in C:\wamp\www\resh\backend.php on line 39

Upvotes: 5

Views: 4267

Answers (1)

Sougata Bose
Sougata Bose

Reputation: 31739

This is happning because array_map() will pass the data which contains an array instead. Try with -

$toReturn = array_map('encode_all_strings', $toReturn);

function encode_all_strings($arr) {
    foreach($arr as $key => $value) {
        $arr[$key] = utf8_encode($value);
    }
    return $arr;
}

Upvotes: 6

Related Questions