JSON_decode() return NULL - php

I am trying to convert JSON plain text to php array but it always returns NULL. Actually, I am building a website which fetches the quran from other website through API. And the text type is ARABIC (utf_8).
Here's my JSON:
{"code":200,"status":"OK","data":[{"identifier":"ur.ahmedali","language":"ur","name":"\u0627\u062d\u0645\u062f \u0639\u0644\u06cc","englishName":"Ahmed Ali","format":"text","type":"translation"},{"identifier":"ur.jalandhry","language":"ur","name":"\u062c\u0627\u0644\u0646\u062f\u06c1\u0631\u06cc","englishName":"Fateh Muhammad Jalandhry","format":"text","type":"translation"},{"identifier":"ur.jawadi","language":"ur","name":"\u0639\u0644\u0627\u0645\u06c1 \u062c\u0648\u0627\u062f\u06cc","englishName":"Syed Zeeshan Haider Jawadi","format":"text","type":"translation"},{"identifier":"ur.kanzuliman","language":"ur","name":"\u0627\u062d\u0645\u062f \u0631\u0636\u0627 \u062e\u0627\u0646","englishName":"Ahmed Raza Khan","format":"text","type":"translation"},{"identifier":"ur.qadri","language":"ur","name":"\u0637\u0627\u06c1\u0631 \u0627\u0644\u0642\u0627\u062f\u0631\u06cc","englishName":"Tahir ul Qadri","format":"text","type":"translation"},{"identifier":"ur.junagarhi","language":"ur","name":"\u0645\u062d\u0645\u062f \u062c\u0648\u0646\u0627\u06af\u0691\u06be\u06cc","englishName":"Muhammad Junagarhi","format":"text","type":"translation"},{"identifier":"ur.maududi","language":"ur","name":"\u0627\u0628\u0648\u0627\u0644\u0627\u0639\u0644\u06cc \u0645\u0648\u062f\u0648\u062f\u06cc","englishName":"Abul A'ala Maududi","format":"text","type":"translation"},{"identifier":"ur.khan","language":"ur","name":"Shamshad Ali Khan","englishName":"Shamshad Ali Khan","format":"audio","type":"versebyverse"}]}
I think the problem is because of Arabic characters.
I have tried doing:
utf_unicode(json_decode($str, true));
stripcslashes(json_decode($str, true));
But it never worked
I have everything from other questions similar to mine.
Thanks

You are passing in the wrong parameters to utf_unicode() and stripcslashes(), both of these take a string not an array, json_decode() (in your case) is intended to return an array.
In order to use this JSON string in PHP directly, use PHP's NOWDOC or HEREDOC syntax like below:
Please try:
$str = <<< JSON
{"code":200,"status":"OK","data":[{"identifier":"ur.ahmedali","language":"ur","name":"\u0627\u062d\u0645\u062f \u0639\u0644\u06cc","englishName":"Ahmed Ali","format":"text","type":"translation"},{"identifier":"ur.jalandhry","language":"ur","name":"\u062c\u0627\u0644\u0646\u062f\u06c1\u0631\u06cc","englishName":"Fateh Muhammad Jalandhry","format":"text","type":"translation"},{"identifier":"ur.jawadi","language":"ur","name":"\u0639\u0644\u0627\u0645\u06c1 \u062c\u0648\u0627\u062f\u06cc","englishName":"Syed Zeeshan Haider Jawadi","format":"text","type":"translation"},{"identifier":"ur.kanzuliman","language":"ur","name":"\u0627\u062d\u0645\u062f \u0631\u0636\u0627 \u062e\u0627\u0646","englishName":"Ahmed Raza Khan","format":"text","type":"translation"},{"identifier":"ur.qadri","language":"ur","name":"\u0637\u0627\u06c1\u0631 \u0627\u0644\u0642\u0627\u062f\u0631\u06cc","englishName":"Tahir ul Qadri","format":"text","type":"translation"},{"identifier":"ur.junagarhi","language":"ur","name":"\u0645\u062d\u0645\u062f \u062c\u0648\u0646\u0627\u06af\u0691\u06be\u06cc","englishName":"Muhammad Junagarhi","format":"text","type":"translation"},{"identifier":"ur.maududi","language":"ur","name":"\u0627\u0628\u0648\u0627\u0644\u0627\u0639\u0644\u06cc \u0645\u0648\u062f\u0648\u062f\u06cc","englishName":"Abul A'ala Maududi","format":"text","type":"translation"},{"identifier":"ur.khan","language":"ur","name":"Shamshad Ali Khan","englishName":"Shamshad Ali Khan","format":"audio","type":"versebyverse"}]}
JSON;
$arr = json_decode($str, true);
print_r($arr);
Hope this helps,

Related

Parsing an array from single field

I have a table that has a field that contains what appears to be an array in it. Is there an easy way to convert this into an array that I can work with?
SELECT data FROM exp_cartthrob_item_options_options
Print_r(data);
Returns the following:
a:19:{i:0;a:6:{s:12:"option_value";s:18:"cp-1202-faraglioni";s:11:"option_name";s:16:"1202 Faraglioni ";s:5:"price";s:0:"";s:5:"color";s:5:"Putty";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:1;a:6:{s:12:"option_value";s:21:"cp-1203-scala-fenicia";s:11:"option_name";s:18:"1203 Scala Fenicia";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:2;a:6:{s:12:"option_value";s:19:"cp-1204-castiglione";s:11:"option_name";s:17:"1204 Castiglione ";s:5:"price";s:0:"";s:5:"color";s:5:"Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:3;a:6:{s:12:"option_value";s:19:"cp-1205-villa-jovis";s:11:"option_name";s:17:"1205 Villa Jovis ";s:5:"price";s:0:"";s:5:"color";s:3:"Tan";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:4;a:6:{s:12:"option_value";s:16:"cp-1207-anacapri";s:11:"option_name";s:14:"1207 Anacapri ";s:5:"price";s:0:"";s:5:"color";s:10:"Warm Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:5;a:6:{s:12:"option_value";s:20:"cp-1208-monte-solaro";s:11:"option_name";s:17:"1208 Monte Solaro";s:5:"price";s:0:"";s:5:"color";s:10:"Warm Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:6;a:6:{s:12:"option_value";s:13:"cp-BLCK-black";s:11:"option_name";s:10:"BLCK Black";s:5:"price";s:0:"";s:5:"color";s:6:"Black ";s:13:"grain_texture";s:5:"Full ";s:6:"finish";s:5:"Light";}i:17;a:6:{s:12:"option_value";s:21:"cd-0061-mexican-ochre";s:11:"option_name";s:18:"0061 Mexican Ochre";s:5:"price";s:0:"";s:5:"color";s:10:"Warm Beige";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:18;a:6:{s:12:"option_value";s:12:"cd-0063-soho";s:11:"option_name";s:9:"0063 SoHo";s:5:"price";s:0:"";s:5:"color";s:6:"Orange";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:19;a:6:{s:12:"option_value";s:13:"cd-0064-cocoa";s:11:"option_name";s:10:"0064 Cocoa";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:20;a:6:{s:12:"option_value";s:18:"cd-0065-brownstone";s:11:"option_name";s:15:"0065 Brownstone";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:21;a:6:{s:12:"option_value";s:13:"cd-0066-tabac";s:11:"option_name";s:10:"0066 Tabac";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:22;a:6:{s:12:"option_value";s:18:"cd-0067-toro-black";s:11:"option_name";s:15:"0067 Toro Black";s:5:"price";s:0:"";s:5:"color";s:5:"Black";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:23;a:6:{s:12:"option_value";s:23:"cd-0068-sun-dried-brick";s:11:"option_name";s:20:"0068 Sun-Dried Brick";s:5:"price";s:0:"";s:5:"color";s:12:"Medium Brown";s:13:"grain_texture";s:5:"Full ";s:6:"finish";s:5:"Light";}i:24;a:6:{s:12:"option_value";s:14:"cd-0069-gothic";s:11:"option_name";s:11:"0069 Gothic";s:5:"price";s:0:"";s:5:"color";s:5:"Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:25;a:6:{s:12:"option_value";s:23:"cd-0070-rembrandt-brown";s:11:"option_name";s:23:"0070 Rembrandt Brown ";s:5:"price";s:0:"";s:5:"color";s:12:"Medium Brown";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:27;a:6:{s:12:"option_value";s:15:"cd-0078-pompeii";s:11:"option_name";s:12:"0078 Pompeii";s:5:"price";s:0:"";s:5:"color";s:3:"Red";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:30;a:6:{s:12:"option_value";s:21:"cd-0082-gulmard-green";s:11:"option_name";s:18:"0082 Gulmard Green";s:5:"price";s:0:"";s:5:"color";s:10:"Dark Green";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}i:31;a:6:{s:12:"option_value";s:21:"cd-0084-prussian-blue";s:11:"option_name";s:18:"0084 Prussian Blue";s:5:"price";s:0:"";s:5:"color";s:9:"Dark Blue";s:13:"grain_texture";s:4:"Full";s:6:"finish";s:5:"Light";}}
Yes, you can use unserialize() to achieve that:
SELECT data FROM exp_cartthrob_item_options_options
$array = unserialize($data);
var_dump($array);

PHP JSON Google Definitions - accessing a value

EDIT#4: json_decode is failing and returning null on a seemingly valid json string. See below for more info
I am new to JSON/JSONP and I'm running into constant trouble accessing the values in the returned JSON with PHP. I have stripped the JSONP callback without issue using code I found on this board. I am getting a JSONP result from http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=love and struggling to access the first result for the meaning. It's a quite complex result, and I need to access the first meaning (in the node "text") from the below JSON result.
http://pastebin.com/hBTeBTUL
My best attempt was:
if (isset($json->primaries[1]->entries[1]->terms[1]->text))
The above was the best I could do, I just keep getting errors trying to return that text node saying it is undefined. I'd prefer to work with objects rather than associative arrays too, if possible, so please avoid telling me to set it to return assoc array.
Any help would be greatly appreciated. I'm really stuck :P
EDIT:
$json->primaries[1]->entries[1]->terms[0]->text didn't seem to work either. Here is the complete script. Ignore the $params array as it is not used, was going to use it to generate the query.
The script has been edited since when I first posted, I had an invalid JSON object, but the error seems to be fixed as it will now parse through JSON formatters.
The error i'm getting trying to print the value out is
PHP Notice: Trying to get property of non-object in /home/outil2/Plugins/GDefine.php on line 23
EDIT#2: added json_decode which was in my original solution, but got lost in the second version
<?php
class GDefine extends Plugin {
public static $enabled = TRUE;
public function onReceivedData($data) {
if ($data["message"][0] == ".def") {
$params = array (
"callback" => "a",
"sl" => "en",
"tl" => "en",
"q" => $data["message"][1]
);
$jsonp = file_get_contents(
"http://www.google.com/dictionary/json?callback=a&sl=en&tl=en&q=" . $data["message"][1]);
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
var_dump($json);
print_r($json->primaries[1]->entries[1]->terms[0]->text);
if (isset($json->primaries[1]->entries[1]->terms[0]->text)) {
$text = $this->bold("Google Definition: ");
$text .= $this->teal($json->primaries[1]->entries[1]->terms[0]->text);
$this->privmsg($data["target"], $text);
} else {
$this->privmsg($data["target"], "error error error");
}
}
}
}
EDIT #3: this is the string I'm trying to json_decode, after using substr to remove the callback function, but am getting a NULL value returned on var_dump($json)
{"query":"love","sourceLanguage":"en","targetLanguage":"en","primaries":[{"type":"headword","terms":[{"type":"text","text":"love","language":"en","labels":[{"text":"Noun","title":"Part-of-speech"}]},{"type":"phonetic","text":"/lÉv/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/love.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"loves","language":"und","labels":[{"text":"plural"}]}]},{"type":"meaning","terms":[{"type":"text","text":"An intense feeling of deep affection","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"babies fill parents with intense feelings of \x3cem\x3elove\x3c/em\x3e","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"their \x3cb\x3e\x3cem\x3elove\x3c/em\x3e for\x3c/b\x3e their country","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A deep romantic or sexual attachment to someone","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"it was \x3cem\x3elove\x3c/em\x3e at first sight","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"they were both \x3cb\x3ein \x3cem\x3elove\x3c/em\x3e with\x3c/b\x3e her","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"we were slowly \x3cb\x3efalling in \x3cem\x3elove\x3c/em\x3e\x3c/b\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A personified figure of \x3cem\x3elove\x3c/em\x3e, often represented as Cupid","language":"en"}]},{"type":"meaning","terms":[{"type":"text","text":"A great interest and pleasure in something","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"his \x3cb\x3e\x3cem\x3elove\x3c/em\x3e for\x3c/b\x3e football","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"we share a \x3cb\x3e\x3cem\x3elove\x3c/em\x3e of\x3c/b\x3e music","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Affectionate greetings conveyed to someone on one\x27s behalf","language":"en"}]},{"type":"meaning","terms":[{"type":"text","text":"A formula for ending an affectionate letter","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"take care, lots of \x3cem\x3elove\x3c/em\x3e, Judy","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A person or thing that one \x3cem\x3eloves\x3c/em\x3e","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"she was \x3cb\x3ethe \x3cem\x3elove\x3c/em\x3e of his life\x3c/b\x3e","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"their two great \x3cem\x3eloves\x3c/em\x3e are tobacco and whiskey","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"A friendly form of address","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"it\x27s all right, \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Used to express affectionate approval for someone","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"don\x27t fret, there\x27s a \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"(in tennis, squash, and some other sports) A score of zero; nil","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"\x3cem\x3elove\x3c/em\x3e fifteen","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"he was down two sets to \x3cem\x3elove\x3c/em\x3e","language":"en"}]}]}]},{"type":"headword","terms":[{"type":"text","text":"love","language":"en","labels":[{"text":"Verb","title":"Part-of-speech"}]},{"type":"phonetic","text":"/lÉv/","language":"und"},{"type":"sound","text":"http://www.gstatic.com/dictionary/static/sounds/de/0/love.mp3","language":"und"}],"entries":[{"type":"related","terms":[{"type":"text","text":"loved","language":"und","labels":[{"text":"past participle"}]},{"type":"text","text":"loves","language":"und","labels":[{"text":"3rd person singular present"}]},{"type":"text","text":"loving","language":"und","labels":[{"text":"present participle"}]},{"type":"text","text":"loved","language":"und","labels":[{"text":"past tense"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Feel a deep romantic or sexual attachment to (someone)","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"do you \x3cem\x3elove\x3c/em\x3e me?","language":"en"}]}]},{"type":"meaning","terms":[{"type":"text","text":"Like very much; find pleasure in","language":"en"}],"entries":[{"type":"example","terms":[{"type":"text","text":"I\x27d \x3cem\x3elove\x3c/em\x3e a cup of tea, thanks","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"I just \x3cem\x3elove\x3c/em\x3e dancing","language":"en"}]},{"type":"example","terms":[{"type":"text","text":"a fun-\x3cem\x3eloving\x3c/em\x3e girl","language":"en"}]}]}]}]}
I json_decode that and it returns NULL :(
You're trying to access an object that doesn't exist. Your code:
if (isset($json->primaries[1]->entries[1]->terms[1]->text)) // Doesn't exist
There's no terms[1] in entries[1] in primaries[1]. There's just 1 item; terms[0]. I think this will work for example:
if (isset($json->primaries[1]->entries[1]->terms[0]->text))
The first item in the array is indexed by 0 not 1, maybe that's your mistake.
Edit:
You also need to decode the JSON, change:
$json = substr($jsonp, 2, strlen($jsonp)-12);
to:
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
Edit:
You need to escape some unescaped characters in the JSON as well. Add this to your code:
Change:
$json = json_decode(substr($jsonp, 2, strlen($jsonp)-12));
to:
$json = substr($jsonp, 2, strlen($jsonp) - 12);
$json = str_replace("\\", "\\\\", $json);
$json = json_decode($json);

json decode changing the value

I have below json array.
{"entries":[{"uid":155551338258538,"photo":"https:\/\/m.ak.fbcdn.net\/profile.ak\/hprofile-ak-prn1\/323887_155551338258538_1152153357_q.jpg","type":"user","text":"shikhadamodar","path":"\/shikha.damodar.1","category":"Madiun","names":["shikhadamodar"],"index_rank":-1,"needs_update":true,"non_title_tokens":"madiun"},{"uid":155551332173428,"photo":"https:\/\/m.ak.fbcdn.net\/profile.ak\/hprofile-ak-snc3\/273318_155551332173428_2131571532_q.jpg","type":"user","text":"shreya damodar","path":"\/my.devprofile","category":"Nilai","names":["shreyadamodar"],"index_rank":-1,"needs_update":true,"non_title_tokens":"nilai"},{"uid":155555587232111,"photo":"https:\/\/m.ak.fbcdn.net\/profile.ak\/hprofile-ak-prn1\/41332_155555587232111_3158_q.jpg","type":"user","text":"neha neha","path": "\/neha.neha34","category":"New York, New York","names":["Neha neha"],"index_rank":-1,"needs_update":true,"non_title_tokens":"new york, new york"}],"token":"1333551453-7","display_token":5,"display_ttl":1333541132}
when i decode this json array, i am getting ,
array(4){["entries"]=>array(3){[0]=>array(10){["uid"]=>float(1.5555133825854E+14)["photo"]=>string(90) "https://m.ak.fbcdn.net/profile.ak/hprofile-ak-prn1/323887_155551338258538_1152153357_q.jpg"["type"]=>string(4) "user"["text"]=>string(13) "shikhadamodar"["path"]=>string(17) "/shikha.damodar.1"["category"]=>string(6) "Madiun"["names"]=>array(1){[0]=>string(13) "shikhadamodar"}["index_rank"]=>int(-1)["needs_update"]=>bool(true)["non_title_tokens"]=>string(6) "madiun"}[1]=>array(10){["uid"]=>float(1.5555133217343E+14)["photo"]=>string(90) "https://m.ak.fbcdn.net/profile.ak/hprofile-ak-snc3/273318_155551332173428_2131571532_q.jpg"["type"]=>string(4) "user"["text"]=>string(14) "shreya damodar"["path"]=>string(14) "/my.devprofile"["category"]=>string(5) "Nilai"["names"]=>array(1){[0]=>string(13) "shreyadamodar"}["index_rank"]=>int(-1)["needs_update"]=>bool(true)["non_title_tokens"]=>string(5) "nilai"}[2]=>array(10){["uid"]=>float(1.5555558723211E+14)["photo"]=>string(83) "https://m.ak.fbcdn.net/profile.ak/hprofile-ak-prn1/41332_155555587232111_3158_q.jpg"["type"]=>string(4) "user"["text"]=>string(9) "neha neha"["path"]=>string(12) "/neha.neha34"["category"]=>string(18) "New York,New York"["names"]=>array(1){[0]=>string(9) "Neha neha"}["index_rank"]=>int(-1)["needs_update"]=>bool(true)["non_title_tokens"]=>string(18) "new york,new york"}}["token"]=>string(12) "1333551453-7"["display_token"]=>int(5)["display_ttl"]=>int(1333541132)}
first UID in json is "uid":155551338258538,
when it comes to array, it becomes ["uid"]=>float(1.5555133825854E+14)
why is it so??
After getting 1.5555133825854E+14 a a reult, ho can i change that to real UID 155551338258538
?
Hope some great coder can help on this.
I found solution of your problem the UID string is long intger hence json_decode is converting it to scientific notation. Try this
print_r(json_decode($arr, false,512, JSON_BIGINT_AS_STRING));

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