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;
}
Related
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 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.
I have from url this
[{"user_id":"3932131","username":"DanielDimitrov","count300":"1677134","count100":"239025","count50":"41207","playcount":"17730","ranked_score":"1413977663","total_score":"7355146958","pp_rank":"35848","level":"95.5852","pp_raw":"1582.26","accuracy":"97.88556671142578","count_rank_ss":"42","count_rank_s":"337","count_rank_a":"120","country":"BG","events":[]}]
and my php is this
$json = file_get_contents('url');
$obj = json_decode($json);
echo $obj->user_id;
echo 'Username: '.$obj['username'].'<br>';
echo 'PP: '.(int)$obj['pp_raw'].'<br>';
echo 'Level: '.(int)$obj['level'].'<br>';
echo 'Play count: '.$obj['playcount'].'<br>';
I try to remove the brackets from the url and the code run but i get it with brackets... How can i remove them?
<?php
$json = '[{"user_id":"3932131","username":"DanielDimitrov","count300":"1677134","count100":"239025","count50":"41207","playcount":"17730","ranked_score":"1413977663","total_score":"7355146958","pp_rank":"35848","level":"95.5852","pp_raw":"1582.26","accuracy":"97.88556671142578","count_rank_ss":"42","count_rank_s":"337","count_rank_a":"120","country":"BG","events":[]}]';
$in = array("[{", "}]");
$out = array("{", "}");
$obj = json_decode(str_replace($in, $out, $json));
echo $obj->user_id;
echo 'Username: '.$obj->username.'<br>';
echo 'PP: '.(int)$obj->pp_raw.'<br>';
echo 'Level: '.(int)$obj->level.'<br>';
echo 'Play count: '.$obj->playcount.'<br>';
?>
$obj is an array with 1 element.
The short fix is, do $obj = $obj[0] first.
Then you can do $obj["user_id"] etc.
simple script gets a json file, strips out extraneous headers, and tried to access a single key/value with no luck. anyone?
CODE
$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos+15);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";
echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj->{'name'}."<HR>";
The results are:
original response =
GET
d41d8cd98f00b204e9800998ecf8427e
Mon, 16 Dec 2013 10:36:23 GMT
/targets/32feaf056b8c46e4a6f5500b6289cf59{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"23029749e4984e2d92dbfb5ff44f8834"}
My Trimmed json is:
{"target_record":{"target_id":"32feaf056b8c46e4a6f5500b6289cf59","name":"Francesca Grace","width":300.0,"active_flag":true,"tracking_rating":5,"reco_rating":""},"status":"success","result_code":"Success","transaction_id":"b427cb1f89544b4c85332ca0ad174848"}
The print_r of the trimmed json prints:
1
using "$obj->{'target_id'}" to get name give me this:
try this:
$postURL = "http://case42.com/ogle/GetTarget.php?targetid=32feaf056b8c46e4a6f5500b6289cf59";
$json = file_get_contents($postURL);
echo "original response = <P>" . $json ."<HR>";
$strip = "target_record";
$mypos = strpos($json, $strip);
$json = substr($json,$mypos-2);
echo "My Trimmed json is: <P>" . $json."<HR>";
$obj = json_decode($json, true);
echo "<P>The print _ r of the trimmed json prints:<P> " . print_r ($json);
echo "<HR>";
echo "using \"\$obj->{'target_id'}\" to get name give me this: ".$obj['tagret_record']['name']."<HR>";
Simple solution: using "true" in the json_decode converts the object to an associative array. Items inside are then accessed at $Array[$key][key].
I am trying to cut results out of the RBL data it pulls back.
Here is the code.
<?
$ips = file("list.inc");
foreach($ips as $ip)
{
$rblurl = 'http://rbl-check.org/rbl_api.php?ipaddress=' . trim($ip);
$boom = fopen($rblurl, "r");
$rbl = stream_get_contents($boom);
echo "</br>";
$data = explode(";",$rbl);
print "<pre>";
print_r($data[0]);
print "</pre>";
echo "</br>";
//fclose($boom);
}
?>
This is the result.
emailbasura;bl.emailbasura.org;nowebsite;notlisted
Sorbs;zombie.dnsbl.sorbs.net;nowebsite;notlisted
msrbl;combined.rbl.msrbl.net;nowebsite;notlisted
nixspam;ix.dnsbl.manitu.net;nowebsite;notlisted
Spamcop;bl.spamcop.net;nowebsite;notlisted
I am trying to cut the first part and the last part so it only displays this.
emailbasura notlisted
Sorbs notlisted
msrbl notlisted
nixspam notlisted
Spamcop notlisted
Any help would be great!
first you need to explode the data by the line breaks not just the delimeter:
$data = explode("\n",$rbl);
once you've done that you just echo out the data:
foreach($data as $item) {
$item = explode(';',$item);
echo $item[0].' '.$item[3];
}
foreach($data as $d)
{
$arr_data = explode(';',$d);
$first_data = $arr_data[0];
$last_data = $arr_data[3];
}
Change here
print "<pre>";
print_r($data[0]);
print "</pre>"
as
print "<pre>";
$spl = split(';', $data[0]);
echo $spl[0] . $spl[3];
print "<pre>";