PHP Convert Windows-1256 encoded text to UTF-8 - php

I am getting Windows-1256 encoded text from the web and nee to convert it to utf-8.
I tried using mb_convert_encoding and iconv but they don't seem to work.
none of them seem to be capable of handling windows-1256.
How to do it?
Edit: More details about the errors.
When trying
mb_convert_encoding($text,"utf-8", "windows-1256");
I get
Message: mb_convert_encoding() [function.mb-convert-encoding]: Illegal character encoding specified
And when i try
iconv("windows-1256", "utf-8", $text);
I get no errors but it returns an empty string

Trying
echo iconv('WINDOWS-1256', 'UTF-8', 'testÍÊ');
...on http://writecodeonline.com/php/ seems to work correctly (produces testأچأٹ)

Try this, should work:
iconv("windows-1256", "utf-8//TRANSLIT//IGNORE", $text)

Check this:
http://rayed.com/wordpress/wp-content/upload/lib.utf2win.php.txt
Apparently he also had some problems, because he wrote this script, if you can reverse that, it might work.
I reversed it for you, try that:
$f[]="\xc2\xac"; $t[]="\x80";
$f[]="\xd9\xbe"; $t[]="\x81";
$f[]="\xc0\x9a"; $t[]="\x82";
$f[]="\xc6\x92"; $t[]="\x83";
$f[]="\xc0\x9e"; $t[]="\x84";
$f[]="\xc0\xa6"; $t[]="\x85";
$f[]="\xc0\xa0"; $t[]="\x86";
$f[]="\xc0\xa1"; $t[]="\x87";
$f[]="\xcb\x86"; $t[]="\x88";
$f[]="\xc0\xb0"; $t[]="\x89";
$f[]="\xd9\xb9"; $t[]="\x8a";
$f[]="\xc0\xb9"; $t[]="\x8b";
$f[]="\xc5\x92"; $t[]="\x8c";
$f[]="\xda\x86"; $t[]="\x8d";
$f[]="\xda\x98"; $t[]="\x8e";
$f[]="\xda\x88"; $t[]="\x8f";
$f[]="\xda\xaf"; $t[]="\x90";
$f[]="\xc0\x98"; $t[]="\x91";
$f[]="\xc0\x99"; $t[]="\x92";
$f[]="\xc0\x9c"; $t[]="\x93";
$f[]="\xc0\x9d"; $t[]="\x94";
$f[]="\xc0\xa2"; $t[]="\x95";
$f[]="\xc0\x93"; $t[]="\x96";
$f[]="\xc0\x94"; $t[]="\x97";
$f[]="\xda\xa9"; $t[]="\x98";
$f[]="\xc4\xa2"; $t[]="\x99";
$f[]="\xda\x91"; $t[]="\x9a";
$f[]="\xc0\xba"; $t[]="\x9b";
$f[]="\xc5\x93"; $t[]="\x9c";
$f[]="\xc0\x8c"; $t[]="\x9d";
$f[]="\xc0\x8d"; $t[]="\x9e";
$f[]="\xda\xba"; $t[]="\x9f";
$f[]="\xd8\x8c"; $t[]="\xa1";
$f[]="\xda\xbe"; $t[]="\xaa";
$f[]="\xd8\x9b"; $t[]="\xba";
$f[]="\xd8\x9f"; $t[]="\xbf";
$f[]="\xdb\x81"; $t[]="\xc0";
$f[]="\xd8\xa1"; $t[]="\xc1";
$f[]="\xd8\xa2"; $t[]="\xc2";
$f[]="\xd8\xa3"; $t[]="\xc3";
$f[]="\xd8\xa4"; $t[]="\xc4";
$f[]="\xd8\xa5"; $t[]="\xc5";
$f[]="\xd8\xa6"; $t[]="\xc6";
$f[]="\xd8\xa7"; $t[]="\xc7";
$f[]="\xd8\xa8"; $t[]="\xc8";
$f[]="\xd8\xa9"; $t[]="\xc9";
$f[]="\xd8\xaa"; $t[]="\xca";
$f[]="\xd8\xab"; $t[]="\xcb";
$f[]="\xd8\xac"; $t[]="\xcc";
$f[]="\xd8\xad"; $t[]="\xcd";
$f[]="\xd8\xae"; $t[]="\xce";
$f[]="\xd8\xaf"; $t[]="\xcf";
$f[]="\xd8\xb0"; $t[]="\xd0";
$f[]="\xd8\xb1"; $t[]="\xd1";
$f[]="\xd8\xb2"; $t[]="\xd2";
$f[]="\xd8\xb3"; $t[]="\xd3";
$f[]="\xd8\xb4"; $t[]="\xd4";
$f[]="\xd8\xb5"; $t[]="\xd5";
$f[]="\xd8\xb6"; $t[]="\xd6";
$f[]="\xd8\xb7"; $t[]="\xd8";
$f[]="\xd8\xb8"; $t[]="\xd9";
$f[]="\xd8\xb9"; $t[]="\xda";
$f[]="\xd8\xba"; $t[]="\xdb";
$f[]="\xd9\x80"; $t[]="\xdc";
$f[]="\xd9\x81"; $t[]="\xdd";
$f[]="\xd9\x82"; $t[]="\xde";
$f[]="\xd9\x83"; $t[]="\xdf";
$f[]="\xd9\x84"; $t[]="\xe1";
$f[]="\xd9\x85"; $t[]="\xe3";
$f[]="\xd9\x86"; $t[]="\xe4";
$f[]="\xd9\x87"; $t[]="\xe5";
$f[]="\xd9\x88"; $t[]="\xe6";
$f[]="\xd9\x89"; $t[]="\xec";
$f[]="\xd9\x8a"; $t[]="\xed";
$f[]="\xd9\x8b"; $t[]="\xf0";
$f[]="\xd9\x8c"; $t[]="\xf1";
$f[]="\xd9\x8d"; $t[]="\xf2";
$f[]="\xd9\x8e"; $t[]="\xf3";
$f[]="\xd9\x8f"; $t[]="\xf5";
$f[]="\xd9\x90"; $t[]="\xf6";
$f[]="\xd9\x91"; $t[]="\xf8";
$f[]="\xd9\x92"; $t[]="\xfa";
$f[]="\xc0\x8e"; $t[]="\xfd";
$f[]="\xc0\x8f"; $t[]="\xfe";
$f[]="\xdb\x92"; $t[]="\xff";
function win_to_utf8($str) {
global $f, $t;
return str_replace($t, $f, $str);
}

Related

Cant read a Json file in php

I have a json file that i want to read but the json_decode function in php always returns error the error is number 5 the utf8 one i use the utf8_decode function and try again it gives error number 4 the syntex error one but although i check it on jsonint validator can you guys help me ?
here is the json :
{
"China": [
"Guangzhou",
"Fuzhou",
"Beijing",
"Baotou",
"Hohhot",
"Guiyang",
"Yinchuan",
"Nanjing",
"Changzhou",
"Chuzhou",
"Hefei",
"Jinan",
"Qingdao",
"Harbin",
"Zhaodong",
"Taiyuan",
"Xi'an",
"Xianyang",
"Shenzhen",
"Nanning",
"Zhengzhou",
"Xinxiang",
"Luohe",
"Luoyang",
"Chaoyang",
"Xingyi",
"Foshan",
"Haikou",
"Chengdu",
"Dongguan",
"Mingzhou",
"Chongqing",
"Zhuhai",
"Kunming",
"Wuhan",
"Xiling",
"Huizhou",
"Jiangmen",
"Shantou",
"Changxiacun",
"Zhongshan",
"Lhasa",
"Nanchang",
"Tianjin",
"Shanghai",
"Hebei",
"Shijiazhuang",
"Quanzhou",
"Putian",
"Xiamen",
"Chengyang",
"Zhangzhou",
"Sanming",
"Nanping",
"Baoding",
"Langfang",
"Yantai",
"Binzhou",
"Lanzhou",
"Yueqing",
"Zhongxin",
"Zhoushan",
"Hangzhou",
"Ningbo",
"Wenzhou",
"Changchun",
"Fuyang",
"Jieshou",
"Anqing",
"Wuhu",
"Shishi",
"Shishi",
"Weitang",
"Shenyang",
"Changsha",
"Yongjiawan",
"Lengshuijiang",
"Shijiazhuang",
"Xuchang",
"Suzhou",
"Xuzhou",
"Taizhou",
"Nanyang",
"Xinhua",
"Ürümqi",
"Yan'an Beilu",
"Baotao",
"Macao",
"Wuxi",
"Yangzhou",
"Baiyin",
"Tongren",
"Kunshan",
"Zhangjiagang"
]
}
and here is the php code :
<?php
$str=file_get_contents("countriesToCities.json");
$json =json_decode($str,true);
print_r( $json['China']);
?>
I have the same problem when i'm using utf8 with bom. The simplest way is remove it for example by this: function

PHP mixed UTF-8 encoding reading CSV

I have a problem where I thought it was easy to Google but it seems to be not that easy. Ok, here is my problem:
I have to read a CSV file which has a bad and different encoding. I'm not able to correct the CSV file before hand, so I have to handle it in my application. So the CSV file could have the following-encodings:
'Ü5' and 'Möbelmarkt' in the same file.
If I decode (utf8_decode) the right one is correct and the left (which was correct) is wrong. When I try to find out the encoding (mb_detect_encoding) i always get the answer that this is UTF-8.
I still tried the following solutions:
public function convert( $str ) {
return iconv( "Windows-1252", "UTF-8", $str );
}
and
private function getUmlauteArray() {
return array( 'ü'=>'ü', 'ä'=>'ä', 'ö'=>'ö', 'Ö'=>'Ö', 'ß'=>'ß', 'à '=>'à', 'á'=>'á', 'â'=>'â', 'ã'=>'ã', 'ù'=>'ù', 'ú'=>'ú', 'û'=>'û', 'Ù'=>'Ù', 'Ú'=>'Ú', 'Û'=>'Û', 'Ãœ'=>'Ü', 'ò'=>'ò', 'ó'=>'ó', 'ô'=>'ô', 'è'=>'è', 'é'=>'é', 'ê'=>'ê', 'ë'=>'ë', 'À'=>'À', 'Ã'=>'Á', 'Â'=>'Â', 'Ã'=>'Ã', 'Ä'=>'Ä', 'Ã…'=>'Å', 'Ç'=>'Ç', 'È'=>'È', 'É'=>'É', 'Ê'=>'Ê', 'Ë'=>'Ë', 'ÃŒ'=>'Ì', 'Ã'=>'Í', 'ÃŽ'=>'Î', 'Ã'=>'Ï', 'Ñ'=>'Ñ', 'Ã’'=>'Ò', 'Ó'=>'Ó', 'Ô'=>'Ô', 'Õ'=>'Õ', 'Ø'=>'Ø', 'Ã¥'=>'å', 'æ'=>'æ', 'ç'=>'ç', 'ì'=>'ì', 'í'=>'í', 'î'=>'î', 'ï'=>'ï', 'ð'=>'ð', 'ñ'=>'ñ', 'õ'=>'õ', 'ø'=>'ø', 'ý'=>'ý', 'ÿ'=>'ÿ', '€'=>'€' );
}
public function fixeUmlaute($string) {
$umlaute = $this->getUmlauteArray();
foreach ($umlaute as $key => $value){
$value = str_replace($key, $value, $string);
}
return $string;
}
and
function valid_utf8( $string ){
return !((bool)preg_match('~[\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF\xC0\xC1]~ms',$string));
}
That are all solutions I found with a Google search to change the encoding...(perhaps this "collection" helps anybody else...) So, how can I really detect the wrong characters or where is it my mistake?
Can anybody give me a hint?
Greetz
V
There is a nice PHP class that can help you with that: https://github.com/neitanod/forceutf8
It will convert any charset to UTF8, and handle the detection for you. Hope it helps.

PHP output JSON Web Service charset UTF-8 error

I am hosting a web service in JSON output by PHP.
I have Hebrew data set in DB and I am posting this as an output to Web service.
When I post the data initially it output the result as follows:
JSON:
{
"tasklist": [
{
"customerID": "9936",
"name": "טר ×רמה ×™×–×•× ×•×‘×™× ×•×™ בע"מ",
"cargo":"×ברר",
"destination":"מכר",
"quantity":"1.000000",
"startdate":"03/01/201300: 00: 00"
}
]
}
But this "×ברר" can be readable by Android/Iphone parser and convert it to original Hebrew. But i faced Error in "name": "טר ×רמה ×™×–×•× ×•×‘×™× ×•×™ בע"מ",. where " is in between the string so the JSON is not valid and shows error!
To Over come this issue I used UTF-8 to convert "×ברר" this to Hebrew "נברר". But in this case too the problem remains same:
PHP:
header('Content-type: text/html; charset=UTF-8');
JSON:
{
"tasklist": [
{
"customerID": "9936",
"name": "טר ארמה יזום ובינוי בע"מ",
"cargo":"נברר",
"destination":"מכר",
"quantity":"1.000000",
"startdate":"03/01/201300: 00: 00"
}
]
}
But still the problem remains:
Also in some case I am getting this � because of using UTF-8
"name":"מחצבות כפר גלעדי-חומרי מ�"
How can I overcome this issue?
Is there any other specific encode I need to use?
Note: The data cannot be changes in Database The solution should be while output to JSON.
How the data stored in DB is shown below:
name
מחצבות כפר גלעדי-חומרי מ×
My PHP Script which output JSON:
<?php
//My DB connection and Query comes here
$jsontext = '{"tasklist":[';
while($row = mysql_fetch_array($queryExe)){
$jsontext .= '{"customerID":"'.$row['AUTO_ID'].'",';
$jsontext .='"name":"'.$row['Customer_Name'].'",';
$jsontext .='"cargo":"'.$row['Type_of_Cargo'].'",';
$jsontext .='"destination":"'.$row['Destination'].'",';
$jsontext .='"quantity":"'.$row['Quantity'].'",';
$jsontext .='"startdate":"'.$row['startdate'].'"},';
}
$jsontext = substr_replace($jsontext, '', -1); // to get rid of extra comma
$jsontext .= "]}";
header('Content-type: text/html; charset=UTF-8');
//Output the final JSON
echo $jsontext;
?>
Thank you for your help in advance!
Was the question clear? to understand my issue.
If your db-field is utf8 you should fist do:
mysql_query("SET NAMES 'utf8'");
You should always do the 'SET NAMES...' before inserting your data, too.
Be sure that you really stored utf8 encoded strings!
then do your query:
mysql_query($your_query);
$array = array("tasklist"=>array());
while($row = mysql_fetch_array($queryExe)){
$a = array();
$a["customerID"] = $row['AUTO_ID'];
$a["name"] = $row['Customer_Name'];
$a["cargo"] = $row['Type_of_Cargo'];
$a["destination"] = $row['Destination'];
$a["quantity"] = $row['Quantity'];
$a["startdate"] = $row['startdate'];
$array["tasklist"][] = $a;
}
header("Content-type: application/json; charset=utf-8");
echo json_encode($array);
exit();
i've made the experience that these is not enough when the servers default charset is for example iso. In that case i need to do the following in my .htaccess:
AddDefaultCharset utf-8
You should change your code to use json_encode. You need to pass it properly utf8 encoded data.
If you are using MySQL you can try running the following before your query to get your data.
SET NAMES 'utf8';
You can also look into using utf8_encode.
From http://www.php.net/manual/en/function.json-encode.php#100565
That said, quotes " will produce invalid JSON, but this is only an issue if you're using json_encode() and just expect PHP to magically escape your quotes. You need to do the escaping yourself.
May be you can replace " with \" , i guess it will solve the issue.
Source : PHP JSON String, escape Double Quotes for JS output

iconv encoding conversion with iconv windows-1256

When encoding the language "UTF-8" to "windows-1256" files I notice letters to lose I do not know why
Example of the text
<?php
$JSON = file_get_contents("http://gdata.youtube.com/feeds/api/videos?q=sUAvgNwQsaM&alt=json");
$JSON_Data = json_decode($JSON);
$title = $JSON_Data->{'feed'}->{'entry'}[0]->{'title'}->{'$t'};
$title= iconv("UTF-8","windows-1256","$title");
echo $youtube;
?>
If it has been deleted
iconv("UTF-8","windows-1256","$title");
Full text will appear and I did not encode windows-1256
How to solve this problem
A text input to databases windows-1256 encoding
Greetings
Try this: (not my code)
$f[]="\xc2\xac"; $t[]="\x80";
$f[]="\xd9\xbe"; $t[]="\x81";
$f[]="\xc0\x9a"; $t[]="\x82";
$f[]="\xc6\x92"; $t[]="\x83";
$f[]="\xc0\x9e"; $t[]="\x84";
$f[]="\xc0\xa6"; $t[]="\x85";
$f[]="\xc0\xa0"; $t[]="\x86";
$f[]="\xc0\xa1"; $t[]="\x87";
$f[]="\xcb\x86"; $t[]="\x88";
$f[]="\xc0\xb0"; $t[]="\x89";
$f[]="\xd9\xb9"; $t[]="\x8a";
$f[]="\xc0\xb9"; $t[]="\x8b";
$f[]="\xc5\x92"; $t[]="\x8c";
$f[]="\xda\x86"; $t[]="\x8d";
$f[]="\xda\x98"; $t[]="\x8e";
$f[]="\xda\x88"; $t[]="\x8f";
$f[]="\xda\xaf"; $t[]="\x90";
$f[]="\xc0\x98"; $t[]="\x91";
$f[]="\xc0\x99"; $t[]="\x92";
$f[]="\xc0\x9c"; $t[]="\x93";
$f[]="\xc0\x9d"; $t[]="\x94";
$f[]="\xc0\xa2"; $t[]="\x95";
$f[]="\xc0\x93"; $t[]="\x96";
$f[]="\xc0\x94"; $t[]="\x97";
$f[]="\xda\xa9"; $t[]="\x98";
$f[]="\xc4\xa2"; $t[]="\x99";
$f[]="\xda\x91"; $t[]="\x9a";
$f[]="\xc0\xba"; $t[]="\x9b";
$f[]="\xc5\x93"; $t[]="\x9c";
$f[]="\xc0\x8c"; $t[]="\x9d";
$f[]="\xc0\x8d"; $t[]="\x9e";
$f[]="\xda\xba"; $t[]="\x9f";
$f[]="\xd8\x8c"; $t[]="\xa1";
$f[]="\xda\xbe"; $t[]="\xaa";
$f[]="\xd8\x9b"; $t[]="\xba";
$f[]="\xd8\x9f"; $t[]="\xbf";
$f[]="\xdb\x81"; $t[]="\xc0";
$f[]="\xd8\xa1"; $t[]="\xc1";
$f[]="\xd8\xa2"; $t[]="\xc2";
$f[]="\xd8\xa3"; $t[]="\xc3";
$f[]="\xd8\xa4"; $t[]="\xc4";
$f[]="\xd8\xa5"; $t[]="\xc5";
$f[]="\xd8\xa6"; $t[]="\xc6";
$f[]="\xd8\xa7"; $t[]="\xc7";
$f[]="\xd8\xa8"; $t[]="\xc8";
$f[]="\xd8\xa9"; $t[]="\xc9";
$f[]="\xd8\xaa"; $t[]="\xca";
$f[]="\xd8\xab"; $t[]="\xcb";
$f[]="\xd8\xac"; $t[]="\xcc";
$f[]="\xd8\xad"; $t[]="\xcd";
$f[]="\xd8\xae"; $t[]="\xce";
$f[]="\xd8\xaf"; $t[]="\xcf";
$f[]="\xd8\xb0"; $t[]="\xd0";
$f[]="\xd8\xb1"; $t[]="\xd1";
$f[]="\xd8\xb2"; $t[]="\xd2";
$f[]="\xd8\xb3"; $t[]="\xd3";
$f[]="\xd8\xb4"; $t[]="\xd4";
$f[]="\xd8\xb5"; $t[]="\xd5";
$f[]="\xd8\xb6"; $t[]="\xd6";
$f[]="\xd8\xb7"; $t[]="\xd8";
$f[]="\xd8\xb8"; $t[]="\xd9";
$f[]="\xd8\xb9"; $t[]="\xda";
$f[]="\xd8\xba"; $t[]="\xdb";
$f[]="\xd9\x80"; $t[]="\xdc";
$f[]="\xd9\x81"; $t[]="\xdd";
$f[]="\xd9\x82"; $t[]="\xde";
$f[]="\xd9\x83"; $t[]="\xdf";
$f[]="\xd9\x84"; $t[]="\xe1";
$f[]="\xd9\x85"; $t[]="\xe3";
$f[]="\xd9\x86"; $t[]="\xe4";
$f[]="\xd9\x87"; $t[]="\xe5";
$f[]="\xd9\x88"; $t[]="\xe6";
$f[]="\xd9\x89"; $t[]="\xec";
$f[]="\xd9\x8a"; $t[]="\xed";
$f[]="\xd9\x8b"; $t[]="\xf0";
$f[]="\xd9\x8c"; $t[]="\xf1";
$f[]="\xd9\x8d"; $t[]="\xf2";
$f[]="\xd9\x8e"; $t[]="\xf3";
$f[]="\xd9\x8f"; $t[]="\xf5";
$f[]="\xd9\x90"; $t[]="\xf6";
$f[]="\xd9\x91"; $t[]="\xf8";
$f[]="\xd9\x92"; $t[]="\xfa";
$f[]="\xc0\x8e"; $t[]="\xfd";
$f[]="\xc0\x8f"; $t[]="\xfe";
$f[]="\xdb\x92"; $t[]="\xff";
function utf8_to_win($str) {
global $f, $t;
return str_replace($f, $t, $str);
}

json_decode returns NULL after webservice call [duplicate]

This question already has answers here:
PHP json_decode() returns NULL with seemingly valid JSON?
(29 answers)
Closed 4 months ago.
There is a strange behaviour with json_encode and json_decode and I can't find a solution:
My php application calls a php web service. The webservice returns json that looks like this:
var_dump($foo):
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
now I like to decode the json in my application:
$data = json_decode($foo, true)
but it returns NULL:
var_dump($data):
NULL
I use php5.
The Content-Type of the response from the webservice: "text/html; charset=utf-8" (also tried to use "application/json; charset=utf-8")
What could be the reason?
Well, i had a similar issue and the problems was the PHP magic quotes in the server... here is my solution:
if(get_magic_quotes_gpc()){
$param = stripslashes($_POST['param']);
}else{
$param = $_POST['param'];
}
$param = json_decode($param,true);
EDIT:
Just did some quick inspection of the string provided by the OP. The small "character" in front of the curly brace is a UTF-8 B(yte) O(rder) M(ark) 0xEF 0xBB 0xBF. I don't know why this byte sequence is displayed as  here.
Essentially the system you aquire the data from sends it encoded in UTF-8 with a BOM preceding the data. You should remove the first three bytes from the string before you throw it into json_decode() (a substr($string, 3) will do).
string(62) "{"action":"set","user":"123123123123","status":"OK"}"
^
|
This is the UTF-8 BOM
As Kuroki Kaze discovered, this character surely is the reason why json_decode fails. The string in its given form is not correctly a JSON formated structure (see RFC 4627)
Print the last json error when debugging.
json_decode( $so, true, 9 );
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
Also use the json.stringify() function to double check your JSON syntax.
None of the solutions above worked for me, but html_entity_decode($json_string) did the trick
Try this
$foo = utf8_encode($foo);
$data = json_decode($foo, true);
make sure that if you sent the data by POST / GET, the server has not escape the quotes
$my_array = json_decode(str_replace ('\"','"', $json_string), true);
"{"action":"set","user":"123123123123","status":"OK"}"
This little apostrophe in the beginning - what is it? First symbol after the doublequote.
I had the similar problem in a live site. In my local site it was working fine. For fixing the same I Just have added the below code
json_decode(stripslashes($_GET['arr']));
I just put this
$result = mb_convert_encoding($result,'UTF-8','UTF-8');
$result = json_decode($result);
and it's working
Yesterday I spent 2 hours on checking and fixing that error finally I found that in JSON string that I wanted to decode were '\' slashes. So the logical thing to do is to use stripslashes function or something similiar to different PL.
Of course the best way is sill to print this var out and see what it becomes after json_decode, if it is null you can also use json_last_error() function to determine the error it will return integer but here are those int described:
0 = JSON_ERROR_NONE
1 = JSON_ERROR_DEPTH
2 = JSON_ERROR_STATE_MISMATCH
3 = JSON_ERROR_CTRL_CHAR
4 = JSON_ERROR_SYNTAX
5 = JSON_ERROR_UTF8
In my case I got output of json_last_error() as number 4 so it is JSON_ERROR_SYNTAX. Then I went and take a look into the string it self which I wanted to convert and it had in last line:
'\'title\' error ...'
After that is really just an easy fix.
$json = json_decode(stripslashes($response));
if (json_last_error() == 0) { // you've got an object in $json}
I had such problem with storage json-string in MySQL.
Don't really know why, but using htmlspecialchars_decode berofe json_decode resolved problem.
Non of these solutions worked for me.
What DID eventually work was checking the string encoding by saving it to a local file and opening with Notepad++.
I found out it was 'UTF-16', so I was able to convert it this way:
$str = mb_convert_encoding($str,'UTF-8','UTF-16');
Maybe you use thing as $ ${: these chars should be quoted.
I was having this problem, when I was calling a soap method to obtain my data, and then return a json string, when I tried to do json_decode I just keep getting null.
Since I was using nusoap to do the soap call I tried to just return json string and now I could do a json_decode, since I really neaded to get my data with a SOAP call, what I did was add ob_start() before include nusoap, id did my call genereate json string, and then before returning my json string I did ob_end_clean(), and GOT MY PROBLEM FIXED :)
EXAMPLE
//HRT - SIGNED
//20130116
//verifica se um num assoc deco é valido
ob_start();
require('/nusoap.php');
$aResponse['SimpleIsMemberResult']['IsMember'] = FALSE;
if(!empty($iNumAssociadoTmp))
{
try
{
$client = new soapclientNusoap(PartnerService.svc?wsdl',
array(
// OPTS
'trace' => 0,
'exceptions' => false,
'cache_wsdl' => WSDL_CACHE_NONE
)
);
//MENSAGEM A ENVIAR
$sMensagem1 = '
<SimpleIsMember>
<request>
<CheckDigit>'.$iCheckDigitAssociado.'</CheckDigit>
<Country>Portugal</Country>
<MemberNumber">'.$iNumAssociadoDeco.'</MemberNumber>
</request>
</SimpleIsMember>';
$aResponse = $client->call('SimpleIsMember',$sMensagem1);
$aData = array('dados'=>$aResponse->xpto, 'success'=>$aResponse->example);
}
}
ob_end_clean();
return json_encode($aData);
I don't know Why?
But this work:
$out = curl_exec($curl);
$out = utf8_encode($out);
$out = str_replace("?", "", $out);
if (substr($out,1,1)!='{'){
$out = substr($out,3);
}
$arResult["questions"] = json_decode($out,true);
without utf8_encode() - Don't work
Check the encoding of your file. I was using netbeans and had to use iso windows 1252 encoding for an old project and netbeans was using this encoding since then for every new file. json_decode will then return NULL. Saving the file again with UTF-8 encoding solved the problem for me.
In Notepad++, select Encoding (from the top menu) and then ensure that "Encode in UTF-8" is selected.
This will display any characters that shouldn't be in your json that would cause json_decode to fail.
Try using json_encode on the string prior to using json_decode... idk if will work for you but it did for me... I'm using laravel 4 ajaxing through a route param.
$username = "{username: john}";
public function getAjaxSearchName($username)
{
$username = json_encode($username);
die(var_dump(json_decode($username, true)));
}
You should try out json_last_error_msg(). It will give you the error message and tell you what is wrong. It was introduced in PHP 5.5.
$foo = "{"action":"set","user":"123123123123","status":"OK"}";
$data = json_decode($foo, true);
if($data == null) {
throw new Exception('Decoding JSON failed with the following message: '
. json_last_error_msg());
}
// ... JSON decode was good => Let's use the data
Before applying PHP related solutions, validate your JSON format. That may be the problem. Try below online JSON format validator. If your JSON format is invalid, correct it first, because PHP doesn't decode invalid JSON strings.
https://jsonformatter.org/
Laravel specific answer:
I got the same issue in Laravel. And this did the trick for me
$result = json_decode($result->getContent(), true);
In my case, when I was printing to the screen, json was fine and I copied and decode with json_deocode() function. It was working fine. But, when I was trying to put jsonString directly in the function, it was returning null because quotes were coming like these ". So I used htmlspecialchars_decode() function and now it is working fine.
I am new here, so if I am making any mistakes in writing answer then sorry for that. I hope it'll help somebody.
Sometimes the problem is generated when the content is compressed, so adding the Accept-Encoding: identity header can solve the problem without having to wrangle with the response.
$opts = array(
'http' =>
array(
'header' =>
array(
'Accept-Encoding: identity',
),
),
);
$context = stream_context_create($opts);
$contents = file_get_contents('URL', false, $context);
i had a similar problem, got it to work after adding '' (single quotes) around the json_encode string. Following from my js file:
var myJsVar = <?php echo json_encode($var); ?> ; -------> NOT WORKING
var myJsVar = '<?php echo json_encode($var); ?>' ; -------> WORKING
just thought of posting it in case someone stumbles upon this post like me :)

Categories