I've been trying to fix this thing for an entire day already and couldn't get it to work. Something which is supposed to be easy.
The problem is, I do a GET request to this URL: http://api.champion.gg/stats?api_key=851a15d4f271849f3beee664ea03db3b
Then, I try to convert the result to a JSON format using the PHP function json_decode. I do it like this:
$httpResponse = drupal_http_request('http://api.champion.gg/stats?api_key=851a15d4f271849f3beee664ea03db3b');
$data = $httpResponse->data;
$datas = json_decode($data);
var_export($datas);
$error = json_last_error_msg();
echo "Error = $error";
And the error message returns "Control character error, possibly incorrectly encoded"
I have already tried using stripslashes, deleting BOM, html_entities, deleting some initial characters and none of them have worked.
You have to set "Accept-Encoding" header to "gzip, deflate", otherwise the response is truncated.
$httpResponse = drupal_http_request('http://api.champion.gg/stats?api_key=851a15d4f271849f3beee664ea03db3b', array('Accept-Encoding' => 'gzip, deflater'));
$data = gzdecode($httpResponse->data);
I'm getting this kind of response from instagram server.
{
"meta": {
"code": 200
},
"data": {
...
},
"pagination": {
"next_url": "...",
"next_max_id": "13872296"
}
}
How do I get the "data" - part? I've tried to json decoding in PHP like:
//$userfeed is giving me something like above.
$tried_this = json_decode($userfeed['meta']);
but $userfeed and $tried_this seems to be the same.
UPDATE
Down below is the REAL data...
I've left out the access token, but otherwise it's correct. This is just a part of it, but I hope you get the picture....
{"pagination":{"next_url":"https://api.instagram.com/v1/users/3/media/recent?access_token=blablabla\u0026max_id=622063574553989866_3","next_max_id":"622063574553989866_3"},"meta":{"code":200},"data":[{"attribution":null,"tags":[],"type":"image","location":{"latitude":21.367158921,"name":"Pali
Lookout","longitude":-157.79304912,"id":60507},"comments":{"count":313,"data":[{"created_time":"1401835727","text":"Can
you give me a shout
out","from":{"username":"nick_putukian1","profile_picture":"http://images.ak.instagram.com/profiles/profile_1370615750_75sq_1401835573.jpg","id":"1370615750","full_name":"Nicholas
Putukian"},"id":"734973811849433422"},{"created_time":"1401836165","text":"I
only have one
follower","from":{"username":"nick_putukian1","profile_picture":"http://images.ak.instagram.com/profiles/profile_1370615750_75sq_1401835573.jpg","id":"1370615750","full_name":"Nicholas
Putukian"},"id":"734977485287985692"},{"created_time":"1401837312","text":"Dear
#kevin could u please add share feature on IG? So users don't have to
screenshoot a foto first if we want to share it.
Thanks.","from":{"username":"natalia.igaa","profile_picture":"http://images.ak.instagram.com/profiles/profile_1003500786_75sq_1401603184.jpg","id":"1003500786","full_name":"Ayu
Natalia"},"id":"734987110351638699"},{"created_time":"1401837882","text":"HI
KEVIN","from":{"username":"gildathegriffon","profile_picture":"http://images.ak.instagram.com/profiles/profile_320785380_75sq_1401742420.jpg","id":"320785380","full_name":"Doivid"},"id":"734991884560110057"},{"created_time":"1401838561","text":"\ud83d\ude02\ud83d\ude02\ud83c\udf42\ud83d\udc9
Forgive me for not giving you a "readable" var_dump, but for some reason the var_dump on a specific server I'm trying on doesn't make it readable as expected.
$data = json_decode($userfeed, true);
var_dump($data['data']);
is returning NULL
Assuming, a valid JSON string, you would do:
$data = json_decode($json_string, true);
var_dump($data['data']);
Lets assume that you have provided access_token, than following syntax will meet your requirements
$url = "https://api.instagram.com/v1/users/3/media/recent/?access_token=ACCESS-TOKEN";
$content = file_get_contents($url);
$data = json_decode($content, true);
var_dump($data['data']);
here is my PHP script.
do2:locu alexus$ cat venuesearch.php
<?php
$KEY='XXXXXXXXXXXXXXX';
$URL='http://api.locu.com/v1_0/venue/search/?api_key=';
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $URL.$KEY);
curl_setopt($ch, CURLOPT_HEADER,0);
print_r(json_decode(curl_exec($ch),TRUE));
?>
do2:locu alexus$
locu service provides output in JSON format. When I run script I'm getting output all in long single line.
sample of output:
do2:locu alexus$ php venuesearch.php
{"meta": {"cache-expiry": 3600, "limit": 25}, "objects": [{"categories": ["restaurant"], "country": "United States",..........
What am I missing? How can I access each of those variables? maybe it makes sense to convert it into XML?
* UPDATE * : .. in example #1 of PHP: json_decode - Manual shows formated output, if I use true then I get array, I'm not getting neither formatet output nor array.
Try adding:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
before execution.
It looks like the execution is simply printing the response rather than returning it as a string to be processed by json_decode.
You should look at the original data:
$json = curl_exec($ch);
var_dump($json);
Your described output is only possible if the API returns a json encoded json string, like that:
"{\"meta\": {\"cache-expiry\": 3600, \"limit\": 25}, \"objects\": [{\"categories\": [\"restaurant\"], \"country\": \"United States\",.......... '
(note the outer quotes, they are part of the string)
This is very weird and definitly a bug in the API but the only way to get around it is to decode it twice:
$data = json_decode(json_decode($json));
Edit: Forget that, Stegrex has figured it out.
I'm trying to connect with the instagram API, the connection works fine and I am receiving the updates just as described in the API documentation, the issue is that I cannot access to the data send to my callback function.
According to the doc
When someone posts a new photo and it triggers an update of one of your subscriptions, we make a POST request to the callback URL that you defined in the subscription
This is my code :
// check if we have a security challenge
if (isset ($_GET['hub_challenge']))
echo $_GET['hub_challenge'];
else // This is an update
{
// read the content of $_POST
$myString = file_get_contents('php://input');
$answer = json_decode($myString);
// This is not working starting from here
$id = $answer->{'object_id'};
$api = 'https://api.instagram.com/v1/locations/'.$id.'/media/recent?client_secret='.INSTA_CLI_SECRET.'&client_id='.INSTA_CLI_ID;
$response = get_curl($api); //change request path to pull different photos
$images = array();
if($response){
$decode = json_decode($response);
foreach($decode->{'data'} as $item){
// do something with the data here
}
}
}
Displaying the $myString variable I have this result, don't know why it is not decoded to json :(
[{"changed_aspect": "media", "subscription_id": 2468174, "object":
"geography", "object_id": "1518250", "time": 1350044500}]
the get_curl function is working fine when I hardcode my $id.
I guess something is wrong with my $myString, unfortunately the $_POST cvariable is not populated, Any idea what I am missing ?
Looking at the example JSON response included in your question, I can conclude that the object you are trying to talk with is wrapped in an array (hence the [ and ] around it in the JSON string).
You should access it using $answers[0]->object_id.
If that doesn't work, you can always use var_dump to check out the data in one of your variables.
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 :)