Cant read a Json file in php - 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

Related

PHP says that this json is invalid because “object property name separator ':' expected”, can anyone see why?

What's wrong with this json:
{ "items" : [ {"timestamp":"1372964400","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1373666400","value":"2","nid":"593141","platform":"-1"},{"timestamp":"1371398400","value":"1","nid":"34872","platform":"-1"},{"timestamp":"1374238800","value":"2","nid":"59251","platform":"-1"},{"timestamp":"1371902400","value":"1","nid":"79534","platform":"-1"},{"timestamp":"1373425200","value":"1","nid":"583657","platform":"-1"},{"timestamp":"1376251200","value":"4","nid":"701275","platform":"-1"},{"timestamp":"1371330000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1372183200","value":"1","nid":"81447","platform":"-1"},{"timestamp":"1372348800","value":"2","nid":"83560","platform":"-1"},{"timestamp":"1373162400","value":"1","nid":"583657","platform":"-1"},{"timestamp":"1374174000","value":"2","nid":"607389","platform":"-1"},{"timestamp":"1371834000","value":"2","nid":"79534","platform":"-1"},{"timestamp":"1372723200","value":"1","nid":"190555","platform":"-1"},{"timestamp":"1373385600","value":"2","nid":"590502","platform":"-1"},{"timestamp":"1375855200","value":"1","nid":"697831","platform":"-1"},{"timestamp":"1372312800","value":"1","nid":"81447","platform":"-1"},{"timestamp":"1373047200","value":"2","nid":"545517","platform":"-1"},{"timestamp":"1373929200","value":"3","nid":"605563","platform":"-1"},{"timestamp":"1375462800","value":"1","nid":"647466","platform":"-1"},{"timestamp":"1376434800","value":"5","nid":"704771","platform":"-1"},{"timestamp":"1371722400","value":"1","nid":"79534","platform":"-1"},{"timestamp":"1372240800","value":"1","nid":"82257","platform":"-1"},{"timestamp":"1372687200","value":"1","nid":"190555","platform":"-1"},{"timestamp":"1373367600","value":"1","nid":"590502","platform":"-1"},{"timestamp":"1374634800","value":"1","nid":"610377","platform":"-1"},{"timestamp":"1375812000","value":"1","nid":"697482","platform":"-1"},{"timestamp":"1372129200","value":"1","nid":"81157","platform":"-1"},{"timestamp":"1372287600","value":"1","nid":"79568","platform":"-1"},{"timestamp":"1372989600","value":"1","nid":"40191","platform":"-1"},{"timestamp":"1373788800","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1375376400","value":"1","nid":"646893","platform":"-1"},{"timestamp":"1376420400","value":"1","nid":"704624","platform":"-1"},{"timestamp":"1371423600","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1372230000","value":"7","nid":"81447","platform":"-1"},{"timestamp":"1372413600","value":"1","nid":"118275","platform":"-1"},{"timestamp":"1373306400","value":"5","nid":"590502","platform":"-1"},{"timestamp":"1374264000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1371960000","value":"1","nid":"79568","platform":"-1"},{"timestamp":"1372924800","value":"1","nid":"82456","platform":"-1"},{"timestamp":"1373558400","value":"3","nid":"590502","platform":"-1"},{"timestamp":"1375092000","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1376280000","value":"1","nid":"701529","platform":"-1"},{"timestamp":"1370044800","value":"1","nid":"68566","platform":"-1"},{"timestamp":"1371380400","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1372183200","value":"3","nid":"81457","platform":"-1"},{"timestamp":"1372352400","value":"1","nid":"83613","platform":"-1"},{"timestamp":"1373194800","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1375689600","value":"1","nid":"687547","platform":"-1"},{"timestamp":"1371902400","value":"2","nid":"59251","platform":"-1"},{"timestamp":"1372762800","value":"1","nid":"212931","platform":"-1"},{"timestamp":"1375977600","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1371322800","value":"2","nid":"59251","platform":"-1"},{"timestamp":"1372179600","value":"1","nid":"81457","platform":"-1"},{"timestamp":"1372345200","value":"2","nid":"83560","platform":"-1"},{"timestamp":"1373068800","value":"1","nid":"545517","platform":"-1"},{"timestamp":"1374163200","value":"1","nid":"607389","platform":"-1"},{"timestamp":"1375470000","value":"1","nid":"647526","platform":"-1"},{"timestamp":"1376460000","value":"1","nid":"705149","platform":"-1"},{"timestamp":"1370278800","value":"1","nid":"57508","platform":"-1"},{"timestamp":"1371765600","value":"2","nid":"79568","platform":"-1"},{"timestamp":"1372690800","value":"1","nid":"212147","platform":"-1"},{"timestamp":"1373382000","value":"9","nid":"590502","platform":"-1"},{"timestamp":"1374674400","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1375819200","value":"1","nid":"697482","platform":"-1"},{"timestamp":"1371132000","value":"1","nid":"76647","platform":"-1"},{"timestamp":"1372143600","value":"1","nid":"81209","platform":"-1"},{"timestamp":"1372302000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1373036400","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1373886000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1375380000","value":"1","nid":"646893","platform":"-1"},{"timestamp":"1376427600","value":"1","nid":"704735","platform":"-1"},{"timestamp":"1370260800","value":"3","nid":"68984","platform":"-1"},{"timestamp":"1372240800","value":"1","nid":"82162","platform":"-1"},{"timestamp":"1372428000","value":"1","nid":"154915","platform":"-1"},{"timestamp":"1373364000","value":"6","nid":"590502","platform":"-1"},{"timestamp":"1374606000","value":"1","nid":"610377","platform":"-1"}] }
when running json_decode on this string php returns null.
i've checked with every online php json_decoder and they decode it succesfully.
i've also tried with json_decode($json, TRUE); but the call also returns NULL
i'm on php version PHP 5.5.1-2+debphp.org~precise+2
I've checked what json_last_error_msg() has to say and it returned:
object property name separator ':' expected
I don't know why you get this error, but it is working fine for me. PHP v5.3.8
$json = '{ "items" : [ {"timestamp":"1372964400","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1373666400","value":"2","nid":"593141","platform":"-1"},{"timestamp":"1371398400","value":"1","nid":"34872","platform":"-1"},{"timestamp":"1374238800","value":"2","nid":"59251","platform":"-1"},{"timestamp":"1371902400","value":"1","nid":"79534","platform":"-1"},{"timestamp":"1373425200","value":"1","nid":"583657","platform":"-1"},{"timestamp":"1376251200","value":"4","nid":"701275","platform":"-1"},{"timestamp":"1371330000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1372183200","value":"1","nid":"81447","platform":"-1"},{"timestamp":"1372348800","value":"2","nid":"83560","platform":"-1"},{"timestamp":"1373162400","value":"1","nid":"583657","platform":"-1"},{"timestamp":"1374174000","value":"2","nid":"607389","platform":"-1"},{"timestamp":"1371834000","value":"2","nid":"79534","platform":"-1"},{"timestamp":"1372723200","value":"1","nid":"190555","platform":"-1"},{"timestamp":"1373385600","value":"2","nid":"590502","platform":"-1"},{"timestamp":"1375855200","value":"1","nid":"697831","platform":"-1"},{"timestamp":"1372312800","value":"1","nid":"81447","platform":"-1"},{"timestamp":"1373047200","value":"2","nid":"545517","platform":"-1"},{"timestamp":"1373929200","value":"3","nid":"605563","platform":"-1"},{"timestamp":"1375462800","value":"1","nid":"647466","platform":"-1"},{"timestamp":"1376434800","value":"5","nid":"704771","platform":"-1"},{"timestamp":"1371722400","value":"1","nid":"79534","platform":"-1"},{"timestamp":"1372240800","value":"1","nid":"82257","platform":"-1"},{"timestamp":"1372687200","value":"1","nid":"190555","platform":"-1"},{"timestamp":"1373367600","value":"1","nid":"590502","platform":"-1"},{"timestamp":"1374634800","value":"1","nid":"610377","platform":"-1"},{"timestamp":"1375812000","value":"1","nid":"697482","platform":"-1"},{"timestamp":"1372129200","value":"1","nid":"81157","platform":"-1"},{"timestamp":"1372287600","value":"1","nid":"79568","platform":"-1"},{"timestamp":"1372989600","value":"1","nid":"40191","platform":"-1"},{"timestamp":"1373788800","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1375376400","value":"1","nid":"646893","platform":"-1"},{"timestamp":"1376420400","value":"1","nid":"704624","platform":"-1"},{"timestamp":"1371423600","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1372230000","value":"7","nid":"81447","platform":"-1"},{"timestamp":"1372413600","value":"1","nid":"118275","platform":"-1"},{"timestamp":"1373306400","value":"5","nid":"590502","platform":"-1"},{"timestamp":"1374264000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1371960000","value":"1","nid":"79568","platform":"-1"},{"timestamp":"1372924800","value":"1","nid":"82456","platform":"-1"},{"timestamp":"1373558400","value":"3","nid":"590502","platform":"-1"},{"timestamp":"1375092000","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1376280000","value":"1","nid":"701529","platform":"-1"},{"timestamp":"1370044800","value":"1","nid":"68566","platform":"-1"},{"timestamp":"1371380400","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1372183200","value":"3","nid":"81457","platform":"-1"},{"timestamp":"1372352400","value":"1","nid":"83613","platform":"-1"},{"timestamp":"1373194800","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1375689600","value":"1","nid":"687547","platform":"-1"},{"timestamp":"1371902400","value":"2","nid":"59251","platform":"-1"},{"timestamp":"1372762800","value":"1","nid":"212931","platform":"-1"},{"timestamp":"1375977600","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1371322800","value":"2","nid":"59251","platform":"-1"},{"timestamp":"1372179600","value":"1","nid":"81457","platform":"-1"},{"timestamp":"1372345200","value":"2","nid":"83560","platform":"-1"},{"timestamp":"1373068800","value":"1","nid":"545517","platform":"-1"},{"timestamp":"1374163200","value":"1","nid":"607389","platform":"-1"},{"timestamp":"1375470000","value":"1","nid":"647526","platform":"-1"},{"timestamp":"1376460000","value":"1","nid":"705149","platform":"-1"},{"timestamp":"1370278800","value":"1","nid":"57508","platform":"-1"},{"timestamp":"1371765600","value":"2","nid":"79568","platform":"-1"},{"timestamp":"1372690800","value":"1","nid":"212147","platform":"-1"},{"timestamp":"1373382000","value":"9","nid":"590502","platform":"-1"},{"timestamp":"1374674400","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1375819200","value":"1","nid":"697482","platform":"-1"},{"timestamp":"1371132000","value":"1","nid":"76647","platform":"-1"},{"timestamp":"1372143600","value":"1","nid":"81209","platform":"-1"},{"timestamp":"1372302000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1373036400","value":"1","nid":"545500","platform":"-1"},{"timestamp":"1373886000","value":"1","nid":"59251","platform":"-1"},{"timestamp":"1375380000","value":"1","nid":"646893","platform":"-1"},{"timestamp":"1376427600","value":"1","nid":"704735","platform":"-1"},{"timestamp":"1370260800","value":"3","nid":"68984","platform":"-1"},{"timestamp":"1372240800","value":"1","nid":"82162","platform":"-1"},{"timestamp":"1372428000","value":"1","nid":"154915","platform":"-1"},{"timestamp":"1373364000","value":"6","nid":"590502","platform":"-1"},{"timestamp":"1374606000","value":"1","nid":"610377","platform":"-1"}] }';
var_dump(json_decode($json));

CodeIgniter $this->post() get incorrect string

I am writing a server script using CodeIgniter to store html code into database. My client send a json package contain a html string:
<table style='width:50%'
but from my server side I can only get from $this->post():
<table >
Do you know what wrong?
My full error log:
My JSON from the client side (encode by $.param from AngularJS):
apikey=superrocket_51f0c7333392f&faqid=31&categoryid=44&question=How+to+format+the+answer+%3F&answer=%3Ctable+style%3D'width%3A50%25%3B'%3E&displayorder=0
My PHP code to handle the JSON:
function updateFAQs_post(){
$auth = $this->_auth();
if ($auth){
print_r($this->post('answer'));
$this->load->model('Admin_model');
$faqid = $this->Admin_model->updateFAQs($this->post('faqid'), $this->post('categoryid'), $this->post('question'), $this->post('answer'), $this->post('displayorder'));
$response = array('success' => 'update done', 'faqid' => $faqid, 'index' => $this->post('index'));
$this->response($response, 200);
}
}
What I get from server:
<table >{"success":"update done","faqid":null,"index":false}
The faqid and index = null is expected. It has nothing to do with the error.
I think the error is due to the difference between the way JavaScript encode and the way PHP decode JSON package ?
try
$this->input->post()
not $this->post()
$_POST works because thats raw php function
I solved the problem by replacing $this->post('answer') by $_POST['answer'].
Still don't know that happened but it works
$this->post('answer');
Should be
$this->input->post('answer');

decoding json data into associative array not working

I have the following code:
$url = "http://myserver/myapp/restapi.php?method=get_list";
$jsondata = curl($url);
print_r($jsondata);
$arrayObjects = json_decode($jsondata, true);
print_r($arrayObjects);
The print out of $jsondata works... but the arrayObjects doesn't print anything.
Ive included just the first "record" of the json data that does get dumped properly:
{"263":{"realm":"object","etags":
[],"id":"263","name":"ddd","label":"","asset_no":null,"objtype_id":"4",
"r_id":null,"R_name":null,"row_id":null,"Row_name":null,"container_id":null,
"container_name":null,"has_problems":"no","comment":null,"nports":"3",
"runs8021Q":"1","itags":[],"dname":"ddd","atags":[{"tag":"$id_263"},
{"tag":"$typeid_4"},{"tag":"$any_object"},{"tag":"$cn_ddd"},{"tag":"$unmounted"},
{"tag":"$no_asset_tag"},{"tag":"$runs_8Q"},{"tag":"$untagged"}]}
},
i'm not getting any error messages displayed on the screen either.
what i did to try to troubleshoot it is to create a new php file that has this json data in it as a string... and then i called json decode. it works fine. check out the code below:
<?php
$jsondata='{"263":{"realm":"object","etags":
[],"id":"263","name":"ddd","label":"","asset_no":null,
"objtype_id":"4","r_id":null,"R_name":null,"row_id":null,
"Row_name":null,"container_id":null,"container_name":null,
"has_problems":"no","comment":null,"nports":"3","runs8021Q":"1","itags":
[],"dname":"ddd","atags":[{"tag":"$id_263"},
{"tag":"$typeid_4"},
{"tag":"$any_object"},{"tag":"$cn_ddd"},{"tag":"$unmounted"},
{"tag":"$no_asset_tag"},{"tag":"$runs_8021Q"},{"tag":"$untagged"}]},"187":
{"realm":"object","etags":[],"id":"187","name":"a-ds-NSM-1",
"label":"","asset_no":null,"objtype_id":"4","r_id":null,
"R_name":null,"row_id":null,"Row_name":null,"container_id":null,
"container_name":null,"has_problems":"no","comment":null,
"nports":"3","runs8021Q":null,"itags":[],
"dname":"ss-a-NSM-1","atags":[{"tag":"$id_187"},{"tag":"$typeid_4"},
{"tag":"$any_object"},{"tag":"$cn_ss-ds-1"},{"tag":"$unmounted"},
{"tag":"$no_asset_tag"},{"tag":"$untagged"}]},
"123":{"realm":"object","etags":
[],"id":"123","name":"df","label":"","asset_no":null,
"objtype_id":"4","r_id":null,"R_name":null,"row_id":null,
"Row_name":null,"container_id":null,"container_name":null,
"has_problems":"no","comment":null,"nports":"3",
"runs8021Q":null,"itags":[],"dname":"df",
"atags":[{"tag":"$id_123"},{"tag":"$typeid_4"},
{"tag":"$any_object"},{"tag":"$cn_df"},
{"tag":"$unmounted"},{"tag":"$no_asset_tag"},{"tag":"$untagged"}]}}';
print_r(json_decode($jsondata,true));
?>
any ideas on what's wrong with my code would be appreciated.
The print out of $jsondata works... but the arrayObjects doesn't print anything.
That probably means the JSON string is invalid. Make sure you have error_reporting on and display_errors = ON so you can see the error. You can also check your PHP error log for the problem.

Extract Data from a Website using PHP

I am trying to get PHP to extract the TOKEN (the uppercase one), USERID (uppercase), and the USER NAME (uppercase) from a web page with the following text.
{
"rsp":{
"stat":"ok",
"auth":{
"token":"**TOKEN**",
"perms":"read",
"user":{
"id":"**USERID**",
"username":"**USER NAME**",
"fullname":"**NAME OF USER**"
}
}
}
}
(This is from the RTM api, getting the authentication token of the user).
How would I go about doing this? Thanks!
EDIT:
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
{
"rsp":{
"stat":"ok",
"tasks":{
"rev":"REV_NUMBER",
"list":{
"id":"ID_NUMBER",
"taskse­­ries":{
"id":"ID_NUMBER",
"created":"2010-11-16T00:01:50Z",
"modified":"2011-02-28T05:09:36Z",
"name":"Buy Milk!",
"source":"js",
"url":"",
"location_id":"",
"rrule":{
"every":"1",
"$t":"FREQ=W­­EEKLY;INTERVAL=1"
},
"tags":[
],
"participants":[
],
"notes":[
],
"task":{
"id":"ID_NUMBER" ­­,
"due":"2011-02-28T05:00:00Z",
"has_due_time":"0",
"added":"2011-02-21T05:04:49Z",
"completed":"",
"deleted":"",
"priority":"2",
"postponed":"0",
"estima­­te":""
}
}
}
}
}
}
As Delan suggested, use json_decode. Here is an example of how you would use json_decode to extract the information you require.
// your json string
$string = '{"rsp":{"stat":"ok","auth":{"token":"**TOKEN**","perms":"read","user":{"id":"**USERID**","username":"**USER NAME**","fullname":"**NAME OF USER**"}}}}';
// parse json string to an array
$array = json_decode($string, true);
// auth token
echo $array['rsp']['auth']['token'];
// user details
echo $array['rsp']['auth']['user']['id'];
echo $array['rsp']['auth']['user']['username'];
echo $array['rsp']['auth']['user']['fullname'];
UPDATE I've updated the code to use json_decode's $assoc parameter to convert from an object to an assoc array.
ANOTHER UPDATE To answer your updated question..
how would i get task name "Buy Milk!" & the due date of the task"2011-02-28T.." using json_decode and php here? Thanks!
This code would work to get the values that you want.
//string(9) "Buy Milk!"
echo $array['rsp']['tasks']['list']['taskseries']['name'];
// string(20) "2011-02-28T05:00:00Z"
echo $array['rsp']['tasks']['list']['taskseries']['task']['due'];
This code isn't ideal, but it gets the job done for you.
If the string is JSON, json_decode in PHP will do the trick. It's was implemented in PHP 5.2.0.
http://www.php.net/manual/en/function.json-decode.php

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