Link to home
Start Free TrialLog in
Avatar of Eduardo Fuerte
Eduardo FuerteFlag for Brazil

asked on

Could you point the reason a value that never evaluates to NULL presents NULL values when creating a JSON file by using PHP?

Hi Experts

Could you point the reason a value that never evaluates to NULL presents NULL values when creating a JSON file by using PHP?

Accordingly to this code:
<?		
while ($reg6 = $bd1->obtenerRegA()) 
{

	//....
	
	
	$period_name = $reg6['tipo_periodo'];
	
	if(is_null($period_name))
	{	
		// --------------NEVER EVALUATES TO NULLL
		print_r('--NULO---');
	}

	//--------------THIS IS CHECKED TO NOT NULL------------------------------
	if(!empty($period_name) and !is_null($period_name) and $period_name!==" ")
	{
			$period_name = $reg6['tipo_periodo'];
	
			$name =	$reg6['nome_completo'];
			 if(!empty($name) or !is_null($name) or $name!==" ")
				$name = $reg6['nome_completo'];
			 else
				$name ='';


			  // Is this the same professional (or the first)
			  if ($reg6['id_profissional'] !== $id_prof_anterior) 
			  {

				$id_prof_anterior = $reg6['id_profissional'];
				$name = $name;
				$nickname='';  
				$email= $reg6['email_profissional'];
				$cellphone= $reg6['celular_profissional'];
				$cooperativa = $reg6['cooperativa'];
				
				
				$tipo_profissional = '';

				if( $reg6['tipo_periodo']===null or empty( $reg6['tipo_periodo']) or  $reg6['tipo_periodo']===' ' ) 
					$tipo_profissional='';
				 else
					$tipo_profissional=$reg6['tipo_periodo'];
				
				$valor_prof =  $reg6['valor_prof'];
				$gender = $reg6['sexo_profissional'];

				$cpf= $reg6['cpf_profissional'];
				
				if(!empty($email) and !is_null($email) and $email!==" ")
				{
					
					// Create the new professional record
					$profs_interno = (object) array('name'=>$name,
					  'nickname'=>'',
					  'email'=>$email,
					  'roles'=>array($papel),
					  'internal_id'=>"CONS:".$conselho.'-'.$identificador_interno,
					  'cellphone'=>$cellphone,
					  'tags'=>array("COOP:".$cooperativa,
					  "FUNC:".$tipo_profissional,
					  "TIPO_PAGAMENTO:".$tipo_pagamento,
					  "VALOR:R$".$valor_prof ),
					  "gender"=>$gender, 
					  "send_invite_when_submit"=>true,
					  'shifts' => [
						(object)[
						  'date' => $reg6['data_entrada_realizada'],
						  'period_name' => $period_name,  //-------------------------------BUT THIS IS PRESENTED AS NULL
						  'valor_shift' => array($valor_prof_shift )
						]
					  ]
					); 
				}
				else
				{

					$profs_interno = (object) array('name'=>$name,
					  'nickname'=>'',
					  'cpf'=>$cpf,
					  'roles'=>array($papel),
					  'internal_id'=>"CONS:".$conselho.'-'.$identificador_interno,
					  'cellphone'=>$cellphone,
					  'tags'=>array("COOP:".$cooperativa,
					  "FUNC:".$tipo_profissional,
					  "TIPO_PAGAMENTO:".$tipo_pagamento,
					  "VALOR:R$".$valor_prof ),
					  "gender"=>$gender, 
					  "send_invite_when_submit"=>true,
					  'shifts' => [
						(object)[
						  'date' => $reg6['data_entrada_realizada'],
						  'period_name' => $period_name,   //-------------------------------BUT THIS IS PRESENTED AS NULL
						  'valor_shift' => array($valor_prof_shift )
						]
					  ]
					); 

			}			

			$profs_total[] = $profs_interno;
		  } 
		  else 
		  {

			$profs_interno->shifts[] = (object)[
			  'date' => $reg6['data_entrada_realizada'],
			  'period_name' => $period_name,
			  'valor_shift' => array($valor_prof_shift )
			];
		  }
	}
}  // Final do while 
?>

Open in new window



But the JSON formed, present NULL(s) at this position.

User generated image
Thanks in advance.
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Eduardo Fuerte

ASKER

Hi Chris

I obtained a sequence of strings like that:

string(21) "T‚c. Enfermagem-08-20"

Open in new window


The unexpected values are  T,c.
Amazingly


Aparently, if I eliminate this T,c.

$nome_per=substr($reg5['tipo_periodo'],4);

Everything goes right ?!
Hmmm. OK, so the value is clearly not NULL, although given the JSON that you've shown above, I would have expected several outputs from the var_dump (one for each loop through the while) not just the one. The JSON you've shown contains an array, so the code that generates that is on line 110.

There's nothing in you code to suggest it should set a value of Null in the final JSON, so another quick check to do is to var_dump the entire object BEFORE you json_encode it and check the values there. You haven't shown us the whole code block, so I can't tell you which line to put that on, but it will need to done after you've populated the object but before you call json_encode on it.
I had a lot of outputs... I just send one as example.
Right OK. The output of the var_dump looks like it contains a comma, but it's not a comma - it's a Single Low-9 Quotation Mark (Unicode 201A), so your problem is likely down to the character set and encoding that you're using.

You should make sure that you're using UTF-8 for your encoding throughout your script
As a quick test, try encoding the value you retrieve from the database:

$period_name = utf8_encode( $reg6['tipo_periodo'] );

See if that works. It should push the value into JSON correctly, as it will UTF8 encode the quotations mark to \u201a
Really, it solves but the JSON has undesired chars..

User generated image
Right. This is definitely an encoding issue. When dealing with characters you want to make sure all parts of your script are using the same encoding. These days, it makes sense to use UTF-8, so you will need to make sure your Database tables are encoded using UTF-8, your DB connection is set to UTF-8 and any output sent to the browser is encoded using UTF-8.

The fact that you're getting odd character tells me that somewhere you have a different encoding. It's probably down to how you store data in your database, so you'd need to check that out. Check the character encoding for the table you're using and also for the connection in your PHP scripts. You can check the table encoding by looking at the table info in PHPMyAdmin.
Couldn't I encode this part of the join ?

...	      , ISNULL(tp.tipo_profissional +'-' + substring(CONVERT(char(8), ep.data_hora_entrada, 108),0,3) +'-'+  substring(CONVERT(char(8), ep.data_hora_saida, 108),0,3),'') AS tipo_periodo";

Open in new window

I have no idea! I've never tried to encode a part of a query. I would suspect that it would cause more problems than it would solve.

Encoding problems are usually caused by a mis-match in the different part s of your setup, so a safer bet would be to ensure all parts of your script are correctly encoded in the first place.

You could try to just set the character type of the output. Try adding this at the very top of your script:

header('Content-type', 'text/html; charset=utf-8');

Open in new window

This will tell your browser that you're outputting the UTF-8 character set.
Unfortunatelly, no success.
I'm going to use this function to sanitize the string....

CREATE FUNCTION dbo.fn_Sanitize (
    @Payload VARCHAR(255)
)
RETURNS VARCHAR(255)
AS
BEGIN
	DECLARE @Result VARCHAR(255) = @Payload;

    IF ( NOT ( @Payload NOT LIKE '%[^A-Z0-9/;.:()_ ]%' ))      

    BEGIN
        SET @Result = (   SELECT   '' + SUBSTRING(a.characters, v.number + 1, 1)
                          FROM     ( SELECT @Payload AS characters ) a
                                   JOIN master.dbo.spt_values v ON v.number < LEN(a.characters)
                          WHERE    v.type = 'P'
                                   AND SUBSTRING(a.characters, v.number + 1, 1) NOT LIKE '%[^A-Z0-9/;.:()_ ]%'
                          ORDER BY v.number ASC
                          FOR XML PATH(''), TYPE ).value('.', 'VARCHAR(255)');
    END;

    SET @Result = REPLACE(@Result, ';','.')
    RETURN @Result;
END;
GO

Open in new window

Chris

Good suggestion.

Thank you