json_encode with non UTF-8 chars

Hi!

I’m trying to develop a simple PHP webservice that returns json.

The data comes from a MS SQL server database.
The data is auto Makes, Models and Trims.

It’s content is portuguese, so I’ll have accented charactes, i.e., á, é, í, ó, ú, ã, etc.

The code:


// get some parameters
$action = isset($_GET['action']) ? $_GET['action'] : '';
$condition = isset($_GET['condition']) ? $_GET['condition'] : '';

// Array used to encode the JSON
$arr = array();
$encodedArray = array();
$marcas = '';
$modelos = '';
$versoes = '';
$detalhes = '';


switch($action)
{
 case "getmarcas":
    $result = mssql_query("exec SP_GetMarcas_Web");

    while($marcas = mssql_fetch_object($result))
    {
      $arr[] = $marcas;
    }

    //$encodedArray = array_map("utf8_encode", $arr);
    //echo json_encode($encodedArray);
    $encodedArray = array_map("utf8_encode", $arr);
	
    echo json_encode($encodedArray);
    break;

  case "getmodelos":
    $result = mssql_query("exec SP_GetModelos_Web $condition");

    while($modelos = mssql_fetch_object($result))
    {
      $arr[] = $modelos;
    }
    echo json_encode($arr);
    break;

  case "getversoes":
    $result = mssql_query("exec SP_GetVersoes_Web2 $condition");

    while($versoes = mssql_fetch_object($result))
    {
      $arr[] = $versoes;
    }
    echo json_encode($arr);
    break;

  case "getdetalhes":
    $result = mssql_query("exec SP_GetFotoVersao_Web $condition");

    while($detalhes = mssql_fetch_object($result))
    {
      $arr[] = $detalhes;
    }
    echo json_encode($arr);
    break;
} //end switch


If I use

$encodedArray = array_map("utf8_encode", $arr);

to convert to utf-8 (because json_encode only accepts utf-8 strings), I get the error:
“Catchable fatal error: Object of class stdClass could not be converted to string” on that line.

If I just do:


echo json_encode($arr);

The strings get cut off at the first accented char.

Can anybody help me out with this?

Thanks!

Maybe you’d consider passing around something less bulky than an array of full-blown objects via json. An array of arrays (switch to mssql_fetch_array) perhaps?

Hi Dan!

Thanks to your guideline, I modified my code as such:


switch($action)
	{
		case "getmarcas":
			/* grab the DATA from the db */
			$query = "exec SP_GetMarcas_Web";
			$result = mssql_query($query,$link) or die('Errant query:  '.$query);
		 
			/* create one master array of the records */
			$marcas = array();
			if(mssql_num_rows($result)) 
			{
				while($marca = mssql_fetch_assoc($result)) 
				{
					$marcas[] = array('marca'=>array_map('utf8_encode',$marca));
				}
			}
		 
			/* output in necessary format */
			if($format == 'json') 
			{
				header('Content-type: application/json');
				echo json_encode(array('marcas'=>$marcas));
			}
			break;

and it’s working like a charm.

Thanks again for pointing me out in the right direction.