Skip to content


json_encode() กับภาษาไทย

เจอปัญหาภาษาไทยกับการใช้งานฟังก์ชั่น json_encode() นั่นก็คือ มันใช้ด้วยกันไม่ได้ ปัญหานี้เกิดขึ้นเฉพาะกับภาษาไทยที่ใช้ชุดตัวอักษร (Character Set) ในกลุ่ม ANSI (เช่น Windows-874, TIS-620) วิธีการแก้ปัญหา ง่ายนิดเดียวคือ การแปลงให้มันเป็น UTF-8 ก่อนด้วยฟังก์ชั่น iconv() แล้วค่อยเอาไปใส่ json_encode() เท่านี้ก็สามารถใช้งานภาษาไทยได้แล้ว

function js_thai_encode($data)
{	// fix all thai elements
	if (is_array($data))
	{
		foreach($data as $a => $b)
		{
			if (is_array($data[$a]))
			{
				$data[$a] = js_thai_encode($data[$a]);
			}
			else
			{
				$data[$a] = iconv("tis-620","utf-8",$b);
			}
		}
	}
	else
	{
		$data =iconv("tis-620","utf-8",$data);
	}
	return $data;
}

ไปดู LIVE DEMO กันเลย

Share

Posted in JavaScript, JSON.

Tagged with , , .


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.

*