Retrieve data (single field) from remote JSON file with PHP - php

i need to extract one field from a JSON file. From other questiones i've manage to come to this code but the output is a blank page. Can you see what this n00b doing wrong?
<?php
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json);
$tasa=$details->USD[0]->transferencia;
echo .$tasa.;
?>
The json file looks like this:
{
"_antibloqueo": {
"mobile": "https://dkqrwi4z9077n.cloudfront.net",
"video": "https://www.youtube.com/embed/videoseries?list=PL6qOmJKmpQ8QMt20uG_dlh9-jzjcvZOxU&showinfo=0",
"corto_alternativo": "https://bit.ly/venezuela911",
"enable_iads": "1",
"alternativo": "68747470733a2f2f643271737267626d6d76366561752e636c6f756466726f6e742e6e6574",
"alternativo2": "68747470733a2f2f73686431613934666462346474697662672e776f726473736c2e6e6574",
"resource_id": "33504 C"
},
"_labels": {
"a": "DOLARTODAY",
"b": "IMPLICITO",
"c": "SIMADI",
"d": "SICAD 2",
"e": "CENCOEX"
},
"_timestamp": {
"epoch": "1434016329",
"fecha": "Junio 11, 2015 05:22 AM",
"fecha_corta": "Jun 11, 2015",
"fecha_nice": "Junio 11, 2015",
"dia": "Jueves",
"dia_corta": "Jue"
},
"USD": {
"transferencia": 414.18,
"transfer_cucuta": 435.00,
"efectivo": 145.72,
"efectivo_real": 357.61,
"promedio": 414.18,
"promedio_real": 195.94,
"cencoex": 6.30,
"sicad1": 12.00,
"sicad2": 195.94,
"dolartoday": 414.18
},
"EUR": {
"transferencia": 466.57,
"transfer_cucuta": 489.98,
"efectivo": 164.14,
"efectivo_real": 402.84,
"promedio": 466.57,
"promedio_real": 220.71,
"cencoex": 7.10,
"sicad1": 13.52,
"sicad2": 220.71,
"dolartoday": 466.57
},
"COL": {
"compra": 6.70,
"venta": 7
},
"GOLD": {
"rate": 1180.0500
},
"USDVEF": {
"rate": 6.3500
},
"USDCOL": {
"rate": 2775.00,
"ratecash": 2396.00,
"ratetrm": 2523.00,
"trmfactor": 0.1,
"trmfactorcash": 0.05
},
"EURUSD": {
"rate": 1.1264
},
"BCV": {
"fecha": "1433824200",
"fecha_nice": "Junio 9, 2015",
"liquidez": "2.457.797.346",
"reservas": "16.867.000"
}
}

You just make mistake in USD[0] and 2 dots when echoing $tasa
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json);
$tasa=$details->USD->transferencia;
echo $tasa;

I have tested your json, you can access data via multidimensional arrays like below:
<?php
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json , true);
print_r( $details['USD']['transferencia'] );
?>

Try this:
$q = "https://s3.amazonaws.com/dolartoday/data.json";
$json = file_get_contents($q);
$details = json_decode($json, TRUE);
var_dump($details['USD']['transferencia']);

Related

get array content from json (telegram api) in php

I have this json code
"result": [
{
"update_id": 74783732,
"message": {
"message_id": 852,
"from": {
"id": ---,
"is_bot": false,
"first_name": "---",
"username": "---",
"language_code": "en"
},
"chat": {
"id": ---,
"first_name": "---",
"username": "---",
"type": "private"
},
"date": 1646306224,
"text": "#username",
"entities": [
{
"offset": 0,
"length": 16,
"type": "mention"
}
]
}
}
]
I can get content from update_id , message, first_name etc.
but I want to get "mention" from type how can i do it?
my code is
here i decode json and get arrays from json and put them in variable and use it in my queries but I cant get mention from entities...
$update = file_get_contents("php://input");
$update_array = json_decode($update, true);
if( isset($update_array["message"]) )
{
$text = $update_array["message"]["text"];
$chat_id = $update_array["message"]["chat"]["id"];
}
if(isset($update_array["message"]["entities"]["type"]) and $update_array=="mention")
{
$get_username = $text;
show_users_by_username($get_username);
}
tnx for helping
$update_array will never be equal to "mention" but $update_array["message"]["entities"]["type"] yes.
Change your condition.

Add data to JSON child array

This is my JSON file(database.json):
{
"doctors": [
{
"ID": "ahmadakhavan",
"pass": "1234",
"name": "Ahmad Akhavan",
"profilePic": "address",
},
{
"ID": "akramparand",
"pass": "1234",
"name": "Akram Parand",
"profilePic": "address",
}
],
"games": [
{
"ID": "shuttlefuel_1",
"locked": "0",
"logo": "gameLogo",
},
{
"ID": "birthdaycake",
"locked": "0",
"logo": "gameLogo",
}
],
"users": [
{
"ID": "alirezapir",
"prescribes": [
{
"doctorName": "doctor1",
"done": "yes",
"gameId": "wordschain"
},
{
"doctorName": "doctor2",
"done": "no",
"gameId": "numberlab"
}
],
"profilePic": "address"
},
{
"ID": "amirdibaei",
"pass": "1234",
"profilePic": "address"
}
]
}
I want to add a child under prescribes array for a specific ID.
Below is what I have done in my PHP code to do this:
<?php
$username = $_REQUEST['name'];
$data = $_REQUEST['data'];
//Load the file
$contents = file_get_contents('./database.json');
$arraydata = json_decode($data,true);
//Decode the JSON data into a PHP array.
$contentsDecoded = json_decode($contents, true );
foreach($contentsDecoded['users'] as $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$item['prescribes'] = Array();
}
array_push($item['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}
exit('0');
exit;
?>
If I echo $item['prescribes'] after the line array_push($item['prescribes'],$arraydata); I see data added to it, but the original file (database.json) won't show new added data.
(meaning that this new data is not added to $contentsDecoded)
You have to change foreach() code like below:-
foreach($contentsDecoded['users'] as &$item){ //& used as call by reference
if($item['ID'] == $username){
$item['prescribes'][] = $arraydata; //assign new value directly
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit;
}
}
Change your foreach to change the $contentsDecoded array:
foreach($contentsDecoded['users'] as $key => $item){
if($item['ID'] == $username){
if(!isset($item['prescribes'])){
$contentsDecoded['users'][$key]['prescribes'] = Array();
}
array_push($contentsDecoded['users'][$key]['prescribes'],$arraydata);
$json = json_encode($contentsDecoded, JSON_UNESCAPED_UNICODE );
file_put_contents('./database.json', $json);
exit('1');
exit;
}
}

Laravel - Format JSON

I have a code that outputs the json result below:
{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}
Now how can I format it in the my desired json format below:
Note* I have to remove some result.
{
"Ghost in the Shell":
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
Will appreciate if anyone can help me please.
I am not sure what is your purpose , but here is what you need
<?php
$json = '{
"Ghost in the Shell": {
"id": 1203,
"Pipeline": {
"id": 6144,
"name": "Pipeline",
"status": "New",
"item_id": 5962,
"TotalTasksOpen": 2
}
}
}';
$array = json_decode($json, true);
$newArray = array();
foreach($array as $key=>$value) {
$newArray[$key] = '';
foreach($value as $k=>$v) {
if(is_array($v)) {
$newArray = array_merge($newArray,$v);
}
}
}
$newJson = json_encode($newArray);
echo $newJson;
?>

Separate json labels and values with php

I have accessed this json file on my website:
[{
"01:03:2016": "410",
"02:03:2016": "200",
"03:03:2016": "380"
}]
I want to use PHP to change the formatting to something like this, where the dates and counts are all values:
[{
"date": "01:03:2016",
"count": "410"
},
{
"date": "02:03:2016",
"count": "200"
},
{
"date": "03:03:2016",
"count": "380"
}]
PHP
$string = file_get_contents("data.json"); // your current json data
$json_a = json_decode($string, true);
$new_json = array();
foreach ($json_a as $key => $value) {
$new_json[] = array("date"=>$key,'count'=>$value);
}
echo json_encode($new_json); //output
data.json file (your current data)
[{
"01:03:2016": "410",
"02:03:2016": "200",
"03:03:2016": "380"
}]

Parsing Duplicatable Form's JSON data to PHP for Mail

I have a form where there are duplicate-able fields and it produces the following JSON data:
{
"mainmember": [
{
"name": "testtest",
"surname": "test",
"id": "8509295266086",
"age": "27",
"gender": "Male",
"townofbirth": "george",
"email": "test#test.com",
"contact": "0112121211",
"passport": "1111111111111",
"postal": "grjiubrwg",
"postal_code": "0010",
"residential": "tytyytyttyytyt",
"residential_code": "4422"
}
],
"dependant1": [
{
"name": "testDUP",
"surname": "testDUP",
"id": "4802235040081",
"age": "64",
"gender": "Male",
"townofbirth": "tehjte",
"cell": "4774811845",
"email": "testDUP",
"passport": "8202255133088",
"relationship": "spouse"
}
],
"dependant2": [
{
"name": "testDUP2",
"surname": "testDUP2",
"id": "1111111111111",
"age": "45",
"gender": "F",
"townofbirth": "knysnasw",
"cell": "0000000000",
"email": "testDUP2",
"passport": "2222222222222",
"relationship": "inlaw"
}
]
}
now the duplicate-able fields are the dependants, in this JSON there's 2 dependant but on duplication it increases to "dependant3, dependant4, dependant5".
Currently when i submit and send to PHP i can count the dependants:
<?php
$json = $_POST['parameters'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
$datasetCount = count($data); // returns count of array items of any array
echo "<h1>There are $datasetCount Dependants</h1>";
$i = 0;
foreach ($data as $each_dep) {
$i++;
echo "<h2>Dependant $i</h2>";
while (list($key, $value) = each ($each_dep)) {
echo "$key: $value<br />";
}
}
?>
and the jQuery send function I'm using:
jQuery('#submit').click(function(){
jQuery('div[class*="mainmember"]').each(function(k, v){
mainmember = {};
mainmember['id'] = '';
$(v).find('.id').each(function(){
mainmember['id'] += $(this).val();
});
mainmember['age'] = '';
$(v).find('.age').each(function(){
mainmember['age'] += $(this).val();
});
mainmember['gender'] = $(v).find('.gender').val();
result['mainmember'] = [mainmember];
});
jQuery('div[class*="dependant"]').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['id'] = '';
$(v).find('.id').each(function(){
dependants['id'] += $(this).val();
});
dependants['age'] = '';
$(v).find('.age').each(function(){
dependants['age'] += $(this).val();
});
dependants['gender'] = $(v).find('.gender').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
I just cant get the other data, such as name, surname etc.
I need to parse it like this to an email:
Main Member:
details
Dependant 2:
details
Dependant 3:
details
Any Help greatly appreciated.
Your json structure is quite painful, you seem to be creating arrays of a single object.
Instead you should have arrays of objects, or single objects referenced by keys.
Ideally for your structure, I think you should have an array of objects for the dependents and a single object for the mainmember, like this:
{
"mainmember": {
"name": "test2",
"id": "1111111111111",
"age": "45",
"gender": "M",
"townofbirth": "knysna",
"email": "tjyrrtjhe",
"contact": "1111111111",
"passport": "5555555555555",
"postal": "yrtjyt",
"postal_code": "1101",
"residential": "tkyutk",
"residential_code": "5555"
},
"dependants": [
{
"name": "dtjtet",
"surname": "grwwr",
"id": "1111222222222",
"age": "48",
"gender": "F",
"townofbirth": "knmysn",
"cell": "0045128588",
"email": "fae#gmail.COM",
"passport": "1212112111111",
"relationship": "spouse"
},
{
"name": "dtjtet2",
"surname": "grwwr2",
"id": "11112222222222",
"age": "44",
"gender": "M",
"townofbirth": "knmysn",
"cell": "0045128588",
"email": "fae#gmail.COM",
"passport": "1212112111111",
"relationship": "spouse"
}
]
}
This way you have a single "mainmember" object, and an array of dependents.
Then with php code like the following you can print the details for it:
<?php
function printMember($member) {
foreach($member as $key=>$value) {
echo "$key : $value <br />";
}
}
$json = $_POST['parameters'];
$json_string = stripslashes($json);
$data = json_decode($json_string, true);
$depCount = count($data["dependants"]);
echo "<h1>There are $depCount Dependants</h1>";
echo "<h2>Main member data:</h2>";
printMember($data["mainmember"]);
foreach ($data["dependants"] as $index => $dependant) {
echo "<h2>Dependant $index</h2>";
printMember($dependant);
}
To create the correct json structure in the jquery code, something like this:
jQuery('#submit').click(function(){
jQuery('div[class*="mainmember"]').each(function(k, v){
mainmember = {};
mainmember['id'] = '';
$(v).find('.id').each(function(){
mainmember['id'] += $(this).val();
});
mainmember['age'] = '';
$(v).find('.age').each(function(){
mainmember['age'] += $(this).val();
});
mainmember['gender'] = $(v).find('.gender').val();
//This is changed: Remove the [] from around the mainmember,
//should be a single object not an array
result['mainmember'] = mainmember;
});
//create the array of dependants
result['dependants'] = [];
jQuery('div[class*="dependant"]').each(function(k, v){
dependant = {};
dependant['id'] = '';
$(v).find('.id').each(function(){
dependant['id'] += $(this).val();
});
dependant['age'] = '';
$(v).find('.age').each(function(){
dependant['age'] += $(this).val();
});
dependant['gender'] = $(v).find('.gender').val();
//add the dependant to the array
result['dependants'].push(dependant);
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
This is untested but should help you proceed. Your problem is because you are using arrays of single objects instead of the object itself.

Categories