Well, I am trying to use json_decode to get a users twitch name via their steam ID, however I am getting an error, and I have read other users issues and I am no closer to fixing it.
Here is my code:
$getcontents = file_get_contents('http://api.twitch.tv/api/steam/76561198049928469');
var_dump(json_decode($getcontents));
$twitchname = $getcontents ['name'];
echo $twitchname;
Here is my error:
Warning: Illegal string offset 'name' in C:\Program Files (x86)\EasyPHP-DevServer-14.1VC11\data\localweb\projects\Portfolio -- Website\forum\index.php on line 29
I have looked at documentation on the dev forums on twitch and I cannot find a way to fix this.
I have also looked at answers on these forums and I cannot find a way to fix this.
Forgot this; vardump output:
object(stdClass)#2 (2) { ["_id"]=> int(59956494) ["name"]=> string(10) "riggster98" }
So the way it works with json_decode is, if you intend to use it like a normal php variable, then you have to pass the true flag into the json_decode function. Then you can use $content['name'] and get the expected results.
But if you want to work with Objects, you can simply just json_decode the content, and then use $content->name to extract the content.
Like this
$getcontents = file_get_contents('http://api.twitch.tv/api/steam/76561198049928469');
$contents = json_decode($getcontents);
echo "<pre>";
print_r($contents->name);
echo "</pre>";
This fixes the issues of not saving the JSON decoded content and passing the parameter to return an array instead of an object:
$getcontents = file_get_contents('http://api.twitch.tv/api/steam/76561198049928469');
$getcontents = json_decode($getcontents, true);
$twitchname = $getcontents['name'];
echo $twitchname;
Related
I try to decode a json file and put it into an array but as soon as there is a special character the json_decode stops working:
$json_file_path = 'creds2.json';
$json_contents = file_get_contents($json_file_path);
$data = json_decode($json_contents, true);
var_dump($data);
returns NULL when creds2.json is:
{
"TEMP_REGEX": "[0-9]{2,3}[\.]{1}[0-9]{1}",
"HUMI_REGEX": "[0-9]{2,3}[\.]{1}[0-9]{1}"
}
but it returns the right value when it's:
{
"example": "examples",
"test123": "test123"
}
I already went around the forums but couldn't find a solution. Even ChatGPT couldn't help me out on this one.
I had to put another ‘\’. It is supposed to be “[\.]”.
I have been stuck in this issue and cant seem to fix it.. I have this JSON STRING
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
I need to convert it into array of object or maybe just one json object.. I have tried doing
json_decode($unBilledArr , true);
It gives me null.
Already tried these solutions as well
Convert a string to JSON object php
https://jonsuh.com/blog/convert-loop-through-json-php-javascript-arrays-objects/
I must be doing something wrong.. cant seem to figure out what..
P.s : This is the response i am getting and i can not do anything about the response.
You are trying to decode an array, either specify the specific item within the array, or make it a string.
For instance:
$unBillableArr = '{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}';
$json = json_decode($unBillableArr, true);
// Or
$unBillableArr = ['{"id":"123", "to":"+923412268656", "MsgReceivedFrom":"03349433314", "message":"Qwertyy", "recdate":"2017-11-20 19:01:49"}'];
$json = json_decode($unBillableArr[0], true);
However, given the string you are receiving does not contain valid JSON and you are unable to control what you receive, I have prepared the following that will replace the single quotes in your JSON, and decode each item into an array:
$unBillableArr = ["{'id' : '123','to' : '+923412268656','MsgReceivedFrom' : '03349433314', 'message':'Qwertyy ', 'recdate':'2017-11-20 19:01:49'}"];
// Loop through each JSON string
$jsonObjects = []; // Change this name...
foreach ($unBillableArr as $jsonString) {
$jsonObjects[] = json_decode(str_replace("'", '"', $jsonString), true);
}
print_r($jsonObjects); // Proof it works
Please bear in mind that I would consider this to be a dirty fix. To fix this properly, you should go back to the source and ensure that the JSON they are returning to you is valid.
I have built an API for my shipping quote system. I feed it values and I get rate quotes back. It works fine but I cannot decode the JSON response. I get a NULL response and I'm not sure whats up. According to validaters the JSON is correct.
So what I essentially do is encode a PHP array on one side and I want to parse that on the other side using a browser and PHP. However, I get a NULL response.
Here is the JSON. Let me know if you need more.
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
I just want to decode this so I can parse it. If there is another way to parse please let me know.
Also, I searched SOF and the similar issues people were having here didn't help me.
This is the code I use to generate the JSON.
<?php
//include ('mysql_connect.php');
$result = mysql_query('select * from quote where user_id = "'.$user_id.'" order by netCharge asc limit 1');
if (!$result) {
die('Could not query:' . mysql_error());
}
if (!$result) echo mysql_error();
$api_data = array();
$api_count = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$api_data[carrier] = $row['carrier'];
$api_data[charge] = $row['netCharge'];
$api_data[service_days] = $row['serviceDays'];
$api_count++;
}
$api_data = json_encode($api_data);
print_r($api_data);
?>
This is what I'm using to grab that JSON data:
<?php
$input = file_get_contents('api_request.php?dest_zip=66101&weight=200&class=50<l_shipment=X&Residential_Delivery=X');
echo $input;
$obj = json_decode($input);
var_dump($obj);
?>
Have you tried the following
$array = json_decode($data, true);
Your response has an extra </div> in it.
Delete the div so that's valid JSON and the decode function will work.
http://trumrates.com/trumrates/rate/quote/signin/api_request.php?dest_zip=66101&weight=200&class=50<l_shipment=X&Residential_Delivery=X
Yields:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
</div>
Summary
The built-in function json_decode (see doc) should help. According to the official document, NULL is returned if the JSON cannot be decoded or if the encoded data is deeper than the recursion limit.
I doubt the JSON string you read is actually NOT as same as PHP reads. Please make sure the string is NOT HTML escaped. And it is very important that keys and values in a JSON should be quoted by double quote. Single quote is malformed JSON, which might be considered as syntax error.
Example
To be a good demo, I put json string in file and then decode it using test.php.
In example.json:
{"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
In test.php:
<?php
$input = file_get_contents('example.json');
echo $input;
// {"carrier":"R&L Carriers","charge":"99.13","service_days":"Wednesday Oct. 22, 2014"}
$obj = json_decode($input);
var_dump($obj);
// object(stdClass)#1 (3) {
// ["carrier"]=>
// string(12) "R&L Carriers"
// ["charge"]=>
// string(5) "99.13"
// ["service_days"]=>
// string(23) "Wednesday Oct. 22, 2014"
// }
When I wrote the code I used 'Enter' to give me spaces between lines of code. For some reason that translated to the JSON and that's why it wasn't working. I just deleted all the extra empty lines in my file and it worked.
foreach ($likes as $like) {
// Extract the pieces of info we need from the requests above
$id = idx($like, 'id');
$item = idx($like, 'name');
fwrite($fileout,json_encode($like));
fwrite($fileout,PHP_EOL );
}
$json_string = file_get_contents('testson.json');
$get_json_values=json_decode($json_string,true);
foreach ($get_json_values as $getlikes) { ?>
<li>
<a href="https://www.facebook.com/<?php echo $getlikes['id']; ?>" target="_top">
</li>
<?php
}
When opening the browser, there is a Warning: Invalid argument supplied for foreach(). I don't understand why would my arguments be invalid.
If I add the if, nothing happens, which shows what the actual problem is. But the question is WHAT IS THE PROPER WAY TO DO THIS? I'm pretty sure it's very simple, but i've been struggling with this for more than an hour. My json files has fields like this, so I don't think there would be the problem:
{"category":"Musician\/band","name":"Yann Tiersen (official)","id":"18359161762"}
Please help me, I really got tired with it, and I don't know what to do. So... how can I decode the file into an array?
You need the contents of the testson.json file not just the name!
Receive the contents via PHP:
$json_string = file_get_contents('testson.json');
Make sure there are valid JSON contents in the file by testing it via
var_dump(json_decode($json_string));
And then call
foreach (json_decode($json_string) as $getlikes) { ?>
Update:
When you save the file and access it miliseconds later it might be that the filesystem is too slow and not showing you the correct content.
Add
fclose($fileout);
clearstatcache();
before the file_get_contents(); call!
I recommend to use file_put_contents() and file_read_contents() to get
rid of such problems!
json_decode is expecting a string as it's first parameter. You are passing what I'm guessing is a filename. You should load the file first like so...
$json = file_get_contents('testson.json');
$data = json_decode($json);
I am trying to get some information about YouTube channel's from the YouTube API.
This is an example the output (using Google's channel), http://gdata.youtube.com/feeds/api/users/Google?alt=json
I am getting the JSON using this:
$json = file_get_contents("http://gdata.youtube.com/feeds/api/users/Google?alt=json");
$data = json_decode($json, true);
I uploaded the output of var_dump($data); to pastebin: http://pastebin.com/CWA7YYGi
What I want to get is totalUploadViews from yt$statistics.
What I have tried so far is:
echo $data['yt$statistics']['totalUploadViews'];
But this gives me an error: Notice: Undefined index: yt$statistics
Not sure what I am doing wrong, would appreciate the help.
yt$statistics is itself a value of a parent array. Try
$data['entry']['yt$statistics']['totalUploadViews'];
The yt$statistics is a key in the array of $data['entry'].
do this:
$json = file_get_contents("http://gdata.youtube.com/feeds/api/users/Google?alt=json");
$data = json_decode($json, true);
echo $data["entry"]["yt\$statistics"]["totalUploadViews"];
the "\$" just escapes the harmful $ from parsing.