Json to url with php - php

In my $output there is this:
{
"status" : "success",
"data" : {
"network" : "BTC",
"addresses" : [
{
"user_id" : 0,
"address" : "3ABR5GohqyXzf2zebYwjmLuwV7vtFZw1BZ",
"label" : "default",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
]
}
}
But now I want it to get to redirect like:
https://example.com/index.php?status=succes&network=BTC
etc. etc.
But $output can change to like:
{
"status" : "success",
"data" : {
"network" : "BTC",
"available_balance" : "0.00000000",
"pending_received_balance" : "0.00000000"
}
}
But then I still want it to work.
I don't know PHP enough for this, so I want to ask:
How to do this?

Simply json_decode() and access the status and network properties:
$decoded = json_decode($output);
header('Location: https://example.com/index.php?status=' . urlencode($decoded->status) . '&network=' . urlencode($decoded->data->network));
exit();

Get the data in the json as an array:
$url = 'https://example.com/index.php?status=' . $status;
foreach($data as $param->$value) {
$url += '&' . $param . '=' . $value
}
header('Location:' $url);
Been a while since i've worked in php but this should handle a varying amount of parameters.

Related

How to decode JSON in a loop using PHP and json_decode?

I have json like this, returned from service:
{
"reports" : {
"name" : "reports"
"response" : {
"build" : {
"version" : "2.55.10.0",
"name" : "reports-app"
}
},
"status" : 200
},
"static-application" : {
"name" : "static-application"
"response" : {
"app" : {
"name" : "client-frontend",
"description" : "Client Static"
},
"build" : {
"version" : "2.55.10.0",
"name" : "client-frontend"
}
},
"status" : 200
},
"static-help" : {
"name" : "static-help"
"response" : {
"app" : {
"name" : "client-frontend",
"description" : "Client Static"
},
"build" : {
"version" : "2.55.8.0",
"name" : "client-frontend"
}
},
"status" : 200
}
}
And I'm trying to decode it with json_decode:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'https://domainname/api/aggregate/info');
$json = curl_exec($ch);
curl_close($ch);
$data = json_decode($json, true);
echo $data['reports']['name']." | ".$data['reports']['response']['build']['version']."<br \>";
echo $data['static-application']['name']." | ".$data['static-application']['response']['build']['version']."<br \>";
echo $data['static-help']['name']." | ".$data['static-help']['response']['build']['version'];
?>
In return i have:
reports | 2.55.10.0
static-application | 2.55.10.0
static-help | 2.55.8.0
Everything works, but when the service will return more modules, I will have to manually add new echo sections.
How can I write the same in a loop?
You may use a foreach loop to iterate over all $data's modules:
$data = json_decode($json, true);
foreach($data as $module => $data)
{
if(isset($data[$module]['name']) && !empty($data[$module]['response']['build']['version']))
{
echo $data[$module]['name']." | ".$data[$module]['response']['build']['version']."<br \>";
}
}
The foreach let you iterate a single element at a time, without the need to manually handle how many elements it contains.
The empty function checks for the presence of the key in the array and if it contains, in the case it may be missed or empty.
If you want to dynamically output the name and build version of the JSON's sections you can use a foreach() loop to iterate over all items:
$data = json_decode($json);
foreach ( $data as $key => $jsonData ) {
echo $jsonData->name;
echo " | ";
echo $jsonData->response->build->version;
}

Telegram bot using PHP - echo doesn't work

I'm trying to use Google Maps API to calculate time and distance between two spots. My code is rather simple and it works (used codepad and it runs smoothly) but when I deploy the code and try to use the service the bot gives me wrong answers...
This is the code:
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false";
$json = file_get_contents($details);
$arr = json_decode($json, TRUE);
$distance = $arr[rows][0][elements][0][distance][text];
$time = $arr[rows][0][elements][0][duration][text];
$response = "You should be there in $time. Total distance you'll cover: $distance";
$parameters = array('chat_id' => $chatId, "text" => $response);
$parameters["method"] = "sendMessage";
echo json_encode($parameters);
This is what the bot answers me:
"You should be there in {. Total distance you'll cover: {";
And this is the actual json:
{
"destination_addresses" : [ "Miami Beach, Florida, Stati Uniti" ],
"origin_addresses" : [ "Miami, Florida, Stati Uniti" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "15,7 km",
"value" : 15745
},
"duration" : {
"text" : "22 min",
"value" : 1322
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
What's going on?!
UPDATE: file_get_contents returns a string. So I decoded it into a PHP array but now the bot doesn't even answer!
$details = "http://maps.googleapis.com/maps/api/distancematrix/json?origins=Miami&destinations=Miami+Beach&mode=driving&sensor=false";
$json = file_get_contents($details);
$JsonObject = json_decode($json);
$distance = $JsonObject->rows[0]->elements[0]->distance->text;
$time = $JsonObject->rows[0]->elements[0]->duration->text;
$response = "You should be there in $time. Total distance you'll cover: $distance";
$chatId = "your telegram id here";
$botToken = "your bot token here";
file_get_contents("https://api.telegram.org/bot$botToken/sendMessage?chat_id=$chatId&text=$response");
This one works with file_get_contents.

JSON to Database with php

So I have this JSON for example
{
"top" : [
{
"info" : {
"ID" : 0,
"TID" : 1
},
"geo" : {
"poins" : [
[
[
-5.9,
57.1
],
[
-5.99,
57.0
]
]
]
}
},
{
"info" : {
"ID" : 1,
"TID" : 2
},
"geo" : {
"points" : [
[
[
-5.4,
57.0
],
[
-5.9,
57.0
]
]
]
}
}
]
}
I need to put this information in the DataBase with php
So I have a colum in the DB called points and it need the data inside to be looking like:
[-5.4, 57.0],[-5.9, 57.0]
I have a columb with ID so all I need is to put the points from the JSON for every ID
My php should be loking like:
connection to the database
$str = file_get_contents(the JSON);
$json = json_decode($str, true);
foreach ($json['top'] as $field) {
query='UPDATE poins_table
SET points='$field['geo']['points']'
WHERE ID='$field['info']['ID']' '
}
The code seems to be not working. What I am missing ...Any siggestions will be helpfull. Thank you
You could try following:
<?php
$str = file_get_contents('the JSON URL');
$json = json_decode($str, true);
try{
$db = new PDO("dbtype:host=yourhost;dbname=yourdbname;charset=utf8","username","password");
$query = $db->prepare('UPDATE poins_table SET points=? WHERE ID=?');
foreach ($json['top'] as $field) {
$query->execute(array(json_encode($field['geo']['points']), $field['info']['ID']));
}
} catch(PDOException $e) {
echo "Error: ". $e;
}
?>

Evaluating a function inside php with if

Im trying to do a loop through a pretty large json file with this function someone else helped me with. But the code below returns with : Warning: Invalid argument supplied for foreach()
This code is executed before the function:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof())
{
$json = json_decode($file->fgets(), true);
var_dump($json);
}
_
function getentry($json)
{
foreach($json as $league)
{
if($league['queue'] == 'RANKED_SOLO_5x5')
{
return $league['entries'][0];
}
return null;
}
}
$entry = getentry($json);
if(isset($entry)) echo $entry['playerOrTeamName'] . ',' . "</br>";
this is the output of var_dump($json); (just a tiny example because its a large file):
{
"_id" : ObjectId("540449a4f59600af7d285075"),
"leagues" : [{
"name" : "Cassiopeia's Hunters",
"tier" : "GOLD",
"queue" : "RANKED_SOLO_5x5",
"entries" : [{
"playerOrTeamId" : "21893177",
"playerOrTeamName" : "JoKoksa",
"division" : "III",
"leaguePoints" : NumberLong(5),
"wins" : NumberLong(99),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Kayle's Patriots",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_3x3",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(64),
"wins" : NumberLong(9),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : false,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}, {
"name" : "Cassiopeia's Infiltrators",
"tier" : "BRONZE",
"queue" : "RANKED_TEAM_5x5",
"entries" : [{
"playerOrTeamId" : "TEAM-ffbaccc0-b8c0-11e2-b67a-782bcb497d6f",
"playerOrTeamName" : "EloStechers",
"division" : "II",
"leaguePoints" : NumberLong(60),
"wins" : NumberLong(11),
"isHotStreak" : false,
"isVeteran" : false,
"isFreshBlood" : false,
"isInactive" : true,
"miniSeries" : false
}],
"id" : NumberLong(21893177)
}],
"summonerId" : NumberLong(21893177),
"region" : "euw",
"updatedAt" : NumberLong(1412719896)
}
EDIT 3:
$file = new SplFileObject("bdfile/summoner_leagues_entries_export.json");
while (!$file->eof()) {
$json = json_decode($file->fgets(), true);
foreach($json['leagues'] as $entry) {
echo $entry['entries'][0]['playerOrTeamName'] . ',' . $entry['tier'] . ',' . $entry['entries'][0]['division'] . ',' . $entry['entries'][0]['leaguePoints'] . ',' . $entry['entries'][0]['wins'] . "<br/>";
}
}
$file = null;
EDIT 4:
I got it fixed, if you are interested, i can paste code here.
I think your line in getentry($json)
foreach($json as $league)
should be
foreach($json['leagues'] as $league)
On reflection. That doesn't look like a vardump. Probably $json is just a string when you get into getentry.
Perhaps you need a bson_decode function before you will be able to treat it like a hash (array)
json_decode won't handle it.
There is one in mongo for php.
http://php.net/manual/en/function.bson-decode.php
But it does say "This function is very beta and entirely useless for 99% of users. It is only useful if you're doing something weird, such as writing your own driver on top of the PHP driver."

how to parse json data in php

I have json result from API like:
{
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
**"pages" : 12**
},
"products" :
[ {"id": "370c3876-a2b9-11e2-b2b4-bc764e10976c", "source_id": "",....}]}
I would like to retrieve "pages" : 12 from pagination. How can I do it?
I tried this and it worked fine
$data = ' {
"pagination":
{
"results" : 2248,
"page" : 1,
"page_size" : 200,
"pages" : 12
}
}';
$response = json_decode($data, true);
echo $response['pagination']['pages'];//12
Use json_decode to decode the api response, then access the property.
Example:
$response = json_decode($data, true);
echo $response['pagination']['pages'];
<?php
$object = json_decode($your_api_return_string);
$pages = $object->pagination->pages;
echo $pages;
?>

Categories