How can I parse this JSON with PHP? - php

How can I parse this JSON, which is supposed to display the items a user has in their Steam inventory.
I have tried this:
$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
echo $data;
It returns the same as just visiting the link. I can't get anything like this to work either:
$id = $json->type;
echo $type;

This is how to get type
$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
foreach ($json->rgDescriptions as $mydata)
{
echo $mydata->type;
}

$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
echo $data;
you are echoing $data that is your input (so you see the same as opening the link directly). To see if the json_decode is working fine you should print $json.
So instead of
echo $data;
use
echo '<pre>'
print_r($json);
echo '</pre>';

$data = file_get_contents('http://steamcommunity.com/id/Mitch8910/inventory/json/440/2/');
$json = json_decode($data);
Now $json has 2 objects.
you can access like.
$json->rgInventory;
$json->success;
if you want to fetch all data from $json->rgInventory;
foreach($json->rgInventory as $e){
//var_dump($e);
echo $e->id;
echo $e->classid;
echo $e->instanceid;
}
etc.

Related

How do i access multiple nested json data

I am having issues accessing the nested data from this. I can access the first top level object but not the nested data. Any suggestions, Thnx
{"userInput":{"relaSource":"DailyMed","relas":"has_EPC","drugName":"intuniv"},"rxclassDrugInfoList":{"rxclassDrugInfo":[{"minConcept":{"rxcui":"40114","name":"Guanfacine","tty":"IN"},"rxclassMinConceptItem":{"classId":"N0000175554","className":"Central alpha-2 Adrenergic Agonist","classType":"EPC"},"rela":"has_EPC","relaSource":"DAILYMED"}]}}
my code is as follows (some functions are tests) but i need to access all datapoints..... relaSource, relas, drugName, rxclassDrugInfoList-> rxclassDrugInfo, minConcept, rxcui, name, tty,
<?php
$url = 'https://rxnav.nlm.nih.gov/REST/rxclass/class/byDrugName.json?drugName=intuniv&relaSource=DailyMed&relas=has_EPC'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
echo $data;
echo "<br/>";
$jsonObj = json_decode($data);
echo "<br/>" . $jsonObj->userInput->relaSource;
echo "<br/>" . $jsonObj->userInput->relas;
echo "<br/>" . $jsonObj->userInput->drugName;
echo "<br/>";
echo "A2";
?>
<?php
foreach ($jsonObj as $data) {
$relaSource = $data->relaSource;
$content = $data->relaSource;
?>
<h1> <?php echo $relaSource; ?></h1>
<h1> <?php echo $content; ?> </h1>
<?php } ?>
$rxclassDrugInfoList = $jsonObj['rxclassDrugInfoList'];
echo $rxclassDrugInfoList['rxclassDrugInfo']."<br/>";
/////////////////////////////////////////////////////////////////////////////
<h2>TEST</h2>
<?php
$url = 'https://rxnav.nlm.nih.gov/REST/rxclass/class/byDrugName.json?drugName=intuniv&relaSource=DailyMed&relas=has_EPC'; // path to your JSON file
$data = file_get_contents($url); // put the contents of the file into a variable
// JSON string
//$someJSON = '[{"name":"Jonathan Suh","gender":"male"},{"name":"William Philbin","gender":"male"},{"name":"Allison McKinnery","gender":"female"}]';
// Convert JSON string to Array
$someArray = json_decode($data, true);
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["userInput"]; // Access Array data
///////////////////////////////////////////////////////////////////////////////////////////
// Convert JSON string to Object
$someObject = json_decode($data);
print_r($someObject); // Dump all data of the Object
echo $someObject[0]->userInput; // Access Object data
// Convert JSON string to Array
$someArray = $someObject[0]->userInput;
print_r($someArray); // Dump all data of the Array
echo $someArray[0]["name"]; // Access Array data
echo "<br/>";
echo "<br/>";
echo "<br/>";
?>
I know it is just a problem with addressing items that are nested incorrectly.
**Here is all the datapoints that u needed **
<?php
$json = '{"userInput":{"relaSource":"DailyMed","relas":"has_EPC","drugName":"intuniv"},"rxclassDrugInfoList":{"rxclassDrugInfo":[{"minConcept":{"rxcui":"40114","name":"Guanfacine","tty":"IN"},"rxclassMinConceptItem":{"classId":"N0000175554","className":"Central alpha-2 Adrenergic Agonist","classType":"EPC"},"rela":"has_EPC","relaSource":"DAILYMED"}]}}';
var_dump($json);
var_dump(json_decode($json)->userInput);
var_dump(json_decode($json)->rxclassDrugInfoList);
var_dump(json_decode($json)->userInput->relaSource);
var_dump(json_decode($json)->userInput->relas);
var_dump(json_decode($json)->userInput->drugName);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->minConcept->rxcui);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->minConcept->name);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->minConcept->tty);
var_dump(json_decode($json)->rxclassDrugInfoList->rxclassDrugInfo[0]->rxclassMinConceptItem->classId);
?>

how to echo fixer.io json php

Hi I'm trying get a json from fixer.io and then for each rates echo it but cant get it to work.
the code are
<?php
function usd(){
echo 'HEJ test';
$fixer_access_key = my_access_key;
$url= 'https://data.fixer.io/api/latest?access_key=' . $fixer_access_key;
echo $url;
$json = file_get_contents($url);
$data = json_decode($json);
echo $url . "<br>";
echo 'printing json foreach <br>';
foreach($data as $obj){
echo '...';
$prefix = $obj;
echo $prefix;
echo '<br>';}
echo 'done printing json foreach';
}
usd(); ?>
and the result are:
https://data.fixer.io/api/latest?access_key=my_fixer_key
printing json foreach
done printing json foreach
instead of
$data = json_decode($json);
use
$data = json_decode($json, true);
This should allow foreacha to works - however you will only see first level of json object keys (not nested ones). The second parameter of json_decode change result from object to array.
You will also need to change foreach - to following: foreach($data as $key => $obj) and inside it echo $obj to echo $key;.
Here is simplified working example.
ALTERNATIVE SOLUTION
If working foreach is not your goal but rather pretty printed json, then instead use following code:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
echo $json_string;

How to JSON decode with \\n in php

I have a JSON structure as below
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
When trying to extract the text and numbers I can do the first step and it works but the nested JSON has \\n and it does not give the text as output
The PHP code is as below
$result = json_decode($json);
print_r($result);
echo "<br>";
foreach($result as $key=>$value){
echo $key.$value;
echo "<br>";
$result_nest = json_decode($value);
echo $result_nest->answerPhrase;
echo "<br>";
Why can I not get the text in answerphrase? It works when the text does not have \\n
You may try the below one. You can replace the \n with some other characters. If you want to display enter in browser then you can replace \n with . Please try the below code and let me know if it worked for you.
<?php
$json = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
$result = json_decode($json);
print_r($result);
echo "\n";
foreach($result as $key=>$value){
echo $key.$value;
echo "<br>";
$value = preg_replace("/\\n/", "___n___", $value);
$result_nest = json_decode($value);
$result_nest->answerPhrase = preg_replace("/___n___/", "\n", $result_nest->answerPhrase);
echo $result_nest->answerPhrase;
echo "<br>";
}
Prefer to fix json before decode and then decode the sub json.
you could do second step in a loop
function test2()
{
$string = '{"Number1":"{\"answerPhrase\":\"\\nTEXT,\\nTEXT
TEXT\\n\",\"dateUpdatedInMillisecond\":1234}"}';
$json = $this->decodeComplexJson($string);
$number = $json->Number1;
//Put this in a loop if you want
$decodedNumber = $this->decodeComplexJson($number);
var_dump($decodedNumber);
echo $decodedNumber->answerPhrase;
}
function decodeComplexJson($string) { # list from www.json.org: (\b backspace, \f formfeed)
$string = preg_replace("/[\r\n]+/", " ", $string);
$json = utf8_encode($string);
$json = json_decode($json);
return $json;
}

parse json from url using php and save in mysql db

I've a JSON response from some web service
{
"success":true,
"timestamp":1503291248,
"quotes":{
"SAD":"ABC",
"LOVE":"XYZ",
"FRIENDSHIP":"SOME",
"ENMITY":"LOREM IPSUM",
... //indicates there are a lot more categories
}
}
I have tried to echo data using this script
<?php
$url = 'MY_URL';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $idx=>$json ) {
echo $idx;
}
?>
this prints
successtermsprivacytimestampsourcequotes
but getting empty response, how can I echo/save above josn data in mySql?
<?php
$url = '{
"success":true,
"timestamp":1503291248,
"quotes":{
"SAD":"ABC",
"LOVE":"XYZ",
"FRIENDSHIP":"SOME",
"ENMITY":"LOREM IPSUM",
... //indicates there are a lot more categories
}
}';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $idx=>$json ) {
if(is_array($json))
{
foreach($json as $iidx=>$jjson)
{
echo $iidx.":".$jjson;
}
}
else
{
echo $idx.":".$json;
}
}
$ins_qry = 'INSERT INTO json_table(jsonvalues) values ("'.$json.'")';
$exec_qry = mysqli_query($link,$ins_qry);
?>
This will print json data.
To save this json data in mysql, you can directly insert the $json value into text column of a MySQL table.
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
Try this..
$url = 'MY_URL';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $val) {
echo $val['success']; //same for other keys
}

json get the right code

Currently trying to get this code to print everything in the array but there is a small
problem.
$json = file_get_contents('https://api.twitch.tv/kraken/channels/zettslive/follows?limit=10&offset=0');
$vid_arr = json_decode($json,true);
$vid_count = count($vid_arr);
foreach ($vid_arr as $vid)
{
echo '<img src="'.$vid[1]['user']['logo'].'">';
}
I have to use the [1] to even get it to work. and I want to be able to echo them all. and not do them one at a time.
$json = file_get_contents('https://api.twitch.tv/kraken/channels/zettslive/follows?limit=10&offset=0');
$vid_arr = json_decode($json,true);
$vid_count = count($vid_arr);
foreach ($vid_arr['follows'] as $follow)
{
echo '<img src="'.$follow['user']['logo'].'">';
}

Categories