Alternative method to display specific JSON data in PHP - php

I am extracting data from a JSON file using a URL like this:
$html5=file_get_contents("url");
$data = json_decode($html5);
echo $data->a->k->f;
This displays $27.58 which is correct.
Here is my JSON data:
{
"a":{
"k":{
"c":"tr",
"f":"$27.58",
"fb":"$30.35",
"ci":"12873809",
"cname":"Cdkeysgame_com",
"ep":"26.05",
"epb":"28.66",
"a":"5473091",
"it":"steam",
"sl":"0",
"l":null,
"lt":null,
"x":0,
"v":"retail",
"ne":0,
"so":0,
"tr":304,
"r":97,
"cf":1,
"p":"27.58317275",
"pb":"30.3467843",
"eci":"865723abbf1cbb952ad4d2da8a8c925e"
},
"k_1":{
"c":"gb",
"f":"$27.64",
"fb":"$30.40",
"ci":"1065801",
"cname":"World_of_games",
"ep":"26.10",
"epb":"28.71",
"a":"781851",
"it":"steam",
"sl":"0",
"l":null,
"lt":null,
"x":0,
"v":"all",
"ne":0,
"so":0,
"tr":1041328,
"r":99,
"cf":1,
"p":"27.6361155",
"pb":"30.39972705",
"eci":"d01a7cacb0e424123985bfe2e53a0523"
},
"k_2":{
"c":"ch",
"f":"$27.68",
"fb":"$30.44",
"ci":"696012",
"cname":"G_hard",
"ep":"26.14",
"epb":"28.75",
"a":"1287052",
"it":"steam",
"sl":"0",
"l":null,
"lt":null,
"x":0,
"v":"retail",
"ne":0,
"so":0,
"tr":10818,
"r":99,
"cf":1,
"p":"27.6784697",
"pb":"30.44208125",
"eci":"a6666c0a47acb70d14b757cd52f1b9cc"
}}
I need to display the same data without using k. For example I want to:
echo $data->a->'Something that specifies first element of 'a' i.e k and not'k_1' and 'k_2'->f;
Since I am scraping this content I cannot change anything like structure or data in this JSON file.

If you just want the first entry under a, then you can decode as an array:
$data = json_decode($json, true);
Then get the first element of $data['a'] and use that. current() will also work:
echo reset($data['a'])['f'];
Or re-index $data['a'] numerically and access the first one 0:
echo array_values($data['a'])[0]['f'];
To catch them all:
foreach($data['a'] as $values) {
echo $values['f'];
//break; if you only want the first one
}

You can do this so:
$object = json_decode($html5);
foreach ($object->a as $element) {
echo $element->f;
}

Related

PHP JSON Search with key name

I have following JSON Data
"12-305":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price":"0"}]
"12-270":[{"catid":"12","fname":"SALADS","ord":"1","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"No Salad","id":"270","icon":"","price":"0"}],
"12-273":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"No Sauce","id":"273","icon":"","price":"0"}],
"15-19":[{"catid":"15","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"12-19":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"15-20":[{"catid":"15","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}],
"12-20":[{"catid":"12","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}]`
I want to only grab rows that contains "catid":"12" or key is like "12-" is this posible with using php json?
$json = json_decode('...your json string...');
$rows_that_contains_catid_12 = array();
$allowed_catid_values = array("12","12-");
foreach($json as &$v) {
foreach($v as &$rv){
if(in_array($rv['catid'],$allowed_catid_values))
$rows_that_contains_catid_12[] = $rv;
}
}
$rows_that_contains_catid_12 holds your result...
Regards
I have found the solution by tweaking the Json key. Removed characters after "-" which left following Json File
"12":[{"catid":"12","fname":"SALADS","ord":"0","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"All Salads","id":"305","icon":"","price":"0"}]
"12":[{"catid":"12","fname":"SALADS","ord":"1","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"6","Valid":"0","Phone":"1","Web":"1","ovalue":"No Salad","id":"270","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"No Sauce","id":"273","icon":"","price":"0"}],
"15":[{"catid":"15","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"2","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"BBQ Sauce","id":"19","icon":"","price":"0"}],
"15":[{"catid":"15","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"2","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}],
"12":[{"catid":"12","fname":"SAUCE","ord":"3","show":"1","free":"0","extra":"0","hasextra":"1","filterorder":"1","maxS":"3","Valid":"0","Phone":"1","Web":"1","ovalue":"Garlic Sauce","id":"20","icon":"","price":"0"}]`
And pulled only key names 12 with this code
//my Json data is stored in a txt file
$catid= 12;
$data= fopen($_SERVER['DOCUMENT_ROOT']."URL TO DATA",'r');
$json = fgets($data);
$subitems =json_decode($json, TRUE);
$subitems =$subitems[$catid];

Get JSON from a URL by PHP

I have a URL that returns a JSON object like this:
{
"USD" : {"15m" : 7809.0, "last" : 7809.0, "buy" : 7809.85, "sell" : 7808.15, "symbol" : "$"},
"AUD" : {"15m" : 10321.42, "last" : 10321.42, "buy" : 10322.54, "sell" : 10320.3, "symbol" : "$"},
}
URL : https://blockchain.info/ticker
more info : https://blockchain.info/api/exchange_rates_api
I want to get all the data from the first line and echo it and to have it keep requesting it so its live
I have used the examples on git hub
https://github.com/blockchain/api-v1-client-php/blob/master/docs/rates.md
but it displays all of the data output and you have to refresh it to get it updated
please can some one point me in the right direction
ideally I would end up with something like
15 m Last Buy Sell
USD ($) 7794.87 7794.87 7795.72 7794.02
I have the table and data going to the table but its echoing the whole data set rather than the first line and also I dont know how to select individual fields
How can I do it through PHP?
What you need is a request php page, which will make:
1 - Get data from te site:
$data = file_get_contents('https://blockchain.info/ticker');
2 - decode the json
$decodedData = json_decode($data);
3 - Here you can access it using OOP:
var_dump($decodedData->USD);
The point here will be to retrieve data as you wish, you can mix it up with HTML in a table for example.
Then, you need a JS script, that will execute a function with setInterval, each few miliseconds. That function should make a request to a PHP page that you created earlier, get that data and change with the updated one.
This Should do it:
<?
$seconds = 5;
function get_live_quote($key){
$json_string = file_get_contents('https://blockchain.info/ticker');
$json_array = json_decode($json_string, TRUE);
$quote = $json_array[$key];
$keys = implode(" ",array_keys($quote));
$values = implode(" ", array_values ($quote));
return "$keys $values \n";
}
while(TRUE){
echo get_live_quote("USD");
sleep($seconds);
}
Save the preceding code to a file like "quote.php". Then from your terminal just run: php quote.php

Printing and parsing JSON variable in PHP

I've the following PHP code with a JSON variable...
$route_geometry_json = "{
\"route_geometry\": [
[44.911537, 7.671326],
[44.911481, 7.671462],
[44.911455, 7.671531],
[44.911434, 7.671602],
[44.911358, 7.671859],
[44.911273, 7.672175],
[44.911198, 7.672458],
[44.91113, 7.672617],
[44.911069, 7.67275],
[44.911003, 7.672821],
[44.910945, 7.672881],
[44.910869, 7.672954],
[44.910868, 7.673046],
[44.91091, 7.673109],
[44.91095, 7.67319],
[44.910964, 7.673266],
[44.910958, 7.673407],
[44.910955, 7.6735],
[44.910947, 7.673632],
[44.910922, 7.673871],
[44.910828, 7.674786],
[44.910711, 7.675816],
[44.910606, 7.676364],
[44.910467, 7.676322],
[44.910368, 7.676308],
[44.910051, 7.676253],
[44.9097, 7.676162],
[44.90944, 7.676041],
[44.909297, 7.675958],
[44.909174, 7.67583],
[44.909107, 7.675722],
[44.908993, 7.675583],
[44.908758, 7.675448],
[44.90796, 7.675037]
]
}";
print "Route geometry -->" + json_encode($route_geometry_json);
The print return "0": any suggestion / example?
I'd like also to extract / print the coords couples like
44.908993, 7.675583
44.908758, 7.675448
Any suggestion will be appreciated ...
Thanks
Cesare
Use this code:
$route_geometry = json_decode($route_geometry_json);
foreach ($route_geometry->route_geometry as $value) {
echo $value[0].', '.$value[1].'<br />';
}
You need to print_r(json_decode($route_geometry_json)) it and not json_encode
json_encode is for creating a JSON string. But since you already have a JSON string already, you need to Decode it to make it an Array/Object.
UPDATE
Your requirement
echo "Route geometry -->";
print_r(json_decode($route_geometry_json));
You cannot concat a String and an Object, so you were getting that Parse error.

Generate the set of data into Json instead of one big mixed Json

How can i create one Json with many small sets of data separated by comma?
Instead of one big Json enclosed by double curly brackets?
I do receive a Json and with php i do use foreach to loop over it, making a lot of data processing inside.
Then generate a new Json, just to avoid the data processing on the client side wich will be processed by angularjs ng-repeat.
All the json data is mixed into one big json set (inside double curly brackets)
My goal is to separate into small sets of data.
I can use the NrType property. In this script the NrType receives the last atribution and just the last received is available.
//The php script
$arr = json_decode($returnedJson); //The original json to be pre-processed
$processedData = "[]";
$processedJson = json_decode($processedData,true);
foreach($arr as $key=>$value) {
foreach($value as $vkey=>$vvalue) {
if( $value[$i]->NrType == 1 ) {
$VlMIni = $value[$i]->QttyInitial;
$VlMSub = $value[$i]->QttyPeriod + $value[$i]->QttyRealAfter;
$VlMRec = $value[$i]->RealValue;
$VlMTotal += $VlMesRece;
//much more data processing going on here ...
} elseif( $value[$i]->NrType == 2 ) {
.
.
.
//and much more data processing going on here ...
}
}
//simple data atribution here
$processedJson['labelDesIni'] = 'Instruments';
$processedJson['labelValueMIni'] = $lblVlMIni;
$processedJson['labelValuePIni'] = $lblVlPlIni;
$processedJson['labelValueAIni'] = $lblVlAIni;
$processedJson['labelValuePAIni'] = $lblVlPAIni;
$processedJson['labelValuePercInic'] = $lblVlPercInic;
$processedJson['labelValuePerc2Inic'] = $lblVlPerc2Inic;
//much more data atribution ...
echo json_encode($processedJson); //the new hgenerated Json
The generated Json :
{
labelDesI: "Inspection",
labelValueMI: "2357",
labelValuePlI: "3914066",
labelValueAI: "1389406",
labelValuePAI: "2431425",
labelValuePercI: 57.143691456656,
labelValuePerc2I: 35.497766261478,
labelDesR: "Instruments",
labelValueMR: "734.54",
labelValuePR: "819.14",
labelValueAR: "660.05",
labelValuePAR: "877.94",
labelValuePercR: 80.087,
labelValuePerc2R: 44.739,
labelDesAcfi: "Fiscalização",
labelValueMAcfi: "343",
labelValuePlAcfi: "29907",
labelValueAAcfi: "16718",
labelValuePAAcfi: "16493",
labelValuePercAcfi: 101.36421512157,
labelValuePerc2Acfi: 55.899956531916,
labelDesT: "Totals",
labelValueMT: 365.59,
labelValuePlT: 547.62,
labelValueAnT: 909.63,
labelValuePAnT: 957.63,
labelValuePercT: 22949,
labelValuePerc2T: 25065
}
The desired format Would be this :
{
label: "Inspection",
labelValue1: "2357",
labelValue2: "3914066",
labelValue3: "1389406",
labelValue4: "2431425",
labelValue5: 57.1456656,
labelValue6: 35.4961478
},
{
labelDesR: "Instruments",
labelValue1: "734.54",
labelValue2: "819.14",
labelValue3: "660.05",
labelValue4: "877.94",
labelValue5: 80.087,
labelValue6: 44.739
},
{
labelDesT: "Totals",
labelValue1: 365.59,
labelValue2: 547.62,
labelValue3: 909.63,
labelValue4: 957.63,
labelValue5: 22949,
labelValue6: 25065
}
Thank´s in advance
generate all of your object separately, create an array of these objects and json_encode the array:
$processedJsonElement[] = ['labelDesT' => "Totals", 'labelValue1' => $whatTheValueIs, . . .];
and add it to you main object:
$processedJson[] = $processedJsonElement;
do this for each section of Json you want to represent. Not sure how you're structuring your Foreach loop as your code doesn't match the output, but whatever you structure is whatever you will will output when you call json_encode.
Basically, you need to structure your foreach loop to be able to compartmentalize the objects you wish to represent as an array of json objects.

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

Categories