2012-05-01 121 views
2

我使用發送JSON消息這PHPPHP JSON與UTF8字符

$result = mysql_query("select a.id, ad.nombre, a.imagen, a.lat, a.long, ad.desc, a.url, a.email, a.tel, a.direccion, a.cp, a.poblacion, a.provincia from `bck_alrededor` a, `bck_alrededor_description` ad, `bck_alrededor_partner` ap 
where a.id = ad.id_alrededor 
and a.id = ap.id_alrededor 
and a.id_cat = '$cat' 
and ad.language = '$idioma' 
and ap.id_partner = '$idp'",$link); 

    while($row = mysql_fetch_array($result)) 
    { 
     $id = $row['id']; 
     $nombre = $row['nombre']; 
     $imagen=$row['imagen']; 
     $lat=$row['lat']; 
     $long=$row['long']; 
     $desc=$row['desc']; 
     $url=$row['url']; 
     $email=$row['email']; 
     $tel=$row['tel']; 
     $direccion=$row['direccion']; 
     $cp=$row['cp']; 
     $poblacion=$row['poblacion']; 
     $provincia=$row['provincia']; 

     if ($imagen <>'') 
     { 
      $imagen = $dir.'/'.$imagen; 
     } 

     $posts[] = array('nid'=> $id , 'title'=> $nombre, 'image'=> $imagen , 'latitude'=> $lat, 'longitude'=> $long, 'html'=> $desc, 'web'=> $url, 'email'=> $email, 'phone'=> $tel, 'address'=> $direccion, 'cp'=> $cp, 'poblacion'=> $poblacion, 'provincia'=> $provincia); 

    } 
    $response['nodes'] = $posts; 

    $current_charset = 'ISO-8859-15'; 
    array_walk_recursive($response,function(&$value) use ($current_charset){ 
     $value = iconv('UTF-8//TRANSLIT',$current_charset,$value); 

    }); 

    echo json_encode($response); 

    if(!headers_sent()) header('Content-Type: application/json; charset=utf-8', true,200); 
    header('Content-type: application/json'); 

但我得到了與此UTF8 JSON消息轉義字符:

{"nodes":[{"nid":"87","title":"Tienda Oficial","image":"\/tiendaoficialgbc.png","latitude":"43.3021","longitude":"-1.9721","html":"Entra y adquiere todos los productos oficiales del GBC. En 48h los tienes en casa","web":"http:\/\/www.gipuzkoabasket.com\/tienda\/tienda_es.php","email":"[email protected]","phone":"943 44 44 28","address":"Paseo de Anoeta 22, 1a Planta","cp":"20014","poblacion":"Donostia - San Sebasti\u00e1n","provincia":"Gipuzkoa"},{"nid":"88","title":"Tienda Oficial Salaberria","image":"\/tiendaoficialgbc.png","latitude":"43.30384","longitude":"-1.9797","html":"Entra y adquiere todos los productos oficiales del GBC. En 48h los tienes en casa","web":"http:\/\/www.gipuzkoabasket.com\/tienda\/tienda_es.php","email":"[email protected]","phone":"943 44 44 28","address":"Jos\u00e9 Maria Salaberria 88","cp":"20014","poblacion":"Donostia - San Sebasti\u00e1n","provincia":""}]} 

我試着使用echo json_encode(utf8_encode($ response));但後來我在客戶端應用程序中收到了一條空的JSON消息。

我怎樣才能得到沒有UTF8字符的常規JSON消息?

感謝

回答

2

\u00e1是爲了逃避JSON Unicode字符一個完全有效的方式。它是JSON規範的一部分。要將其解碼爲UTF-8,只需json_decode即可。 utf8_decode與它無關。

我不明白的是這樣的代碼:

iconv('UTF-8//TRANSLIT',$current_charset,$value); 

這是說你想轉換從UTF-8//TRANSLIT爲ISO-8859-15,這並沒有太大的意義。 //TRANSLIT應該在ISO-8859-15之後,否則你不應該進行這種轉換。

+0

感謝您的指示。這很奇怪,但我的客戶端應用程序JSON解析器給無效的json消息,我無法訪問地址值。 – theomen