Ver Mensaje Individual
  #1 (permalink)  
Antiguo 15/11/2011, 19:22
Avatar de matdj
matdj
 
Fecha de Ingreso: septiembre-2011
Ubicación: General San MartÃ*n, Buenos Aires, Argentina, Argentina
Mensajes: 6
Antigüedad: 12 años, 7 meses
Puntos: 0
Pregunta Problema con JSON, PHP y charset-encoding

Hola todos! como estas? aqui les traigo un problema que no puedo solucionar. A ver si me pueden ayudar!!!

Estoy trabajando con PHP y JSON con las funciones json_encode, json_decode y ademas como estas funciones solo trabajan con charset seteade en UTF-8, utilizo utf8_encode y utf8_decode. Lo que encodeo es un mysql_fetch_Array y lo que desencodeo es un string que posteo y levanto del file_get_contents("php://input").

Aqui viene el problema: NO FUNCIONA EL EL ENCODING!!!!!!!!

cuando encodeo un array con utf8 y luego llamo a la funcion json_encode tengo este resultado por ejemplo:

"title":"Ipod Touch De 8 Gb, 2ra Generaci\u00f3n Exelente Estado"

y cuando posteo un string JSON cuando lo quiero encodear para luego convertirlo a JSON con la funcion json_decode obtengo como resultado:

[title] => Ipod Touch De 8 Gb, 2ra Generacin Exelente Estado

Estoy utilizando los siguientes headers:

header('Content-Type: text/plain');

y les puedo mostrar mi codigo:

Código:
	case 'GET':
		$appID = $_GET['id'];
		$appData = getApplicationData($appID);
		$siteJSON = Array();	
		$appJSON = mysql_fetch_array($appData, MYSQL_ASSOC);
		print getJSON($appJSON);
		break;

	case 'POST':
		$postData = file_get_contents("php://input");
		$postData = json_decode(utf8_encode($postData));
		print_r($postData);
		break;

Código:
function utf8Encode($data){

	if (is_string($data)) {
		return utf8_encode($data);
	}

	if (is_object($data)) {
		$ovs = get_object_vars($data);
		$new = $data;
		foreach ($ovs as $k => $v) {
			$new -> $k = utf8Encode($new -> $k);
		}
		return $new;
	}

	if (!is_array($data)) return $data;

	$ret = Array();

	foreach($data as $i => $d)
	$ret[$i] = utf8Encode($d);
	return $ret;
}

function utf8Decode($dat) {
	if (is_string($dat)) {
		return utf8_decode($dat);
	}

	if (is_object($dat)) {
		$ovs = get_object_vars($dat);
		$new = $dat;
		foreach ($ovs as $k => $v)    {
			$new -> $k = utf8Decode($new -> $k);
		}
		return $new;
	}
	 
	if (!is_array($dat)) {
		return $dat;
	}

	$ret = array();
	foreach($dat as $i=> $d)
	$ret[$i] = utf8Decode($d);
	return $ret;
}

function unsetInternalFields($JSONArray) {
	unset($JSONArray['password']);
	unset($JSONArray['accept_terms']);
	unset($JSONArray['reputation']);
	unset($JSONArray['confirmation_code']);
	return $JSONArray;
}

function getJSON($JSONArray) {
	return str_replace('\\/', '/', formatJSON(json_encode(utf8Encode(unsetInternalFields($JSONArray)))));
}