I made a script to return IDs to me based on if a point is within a polygon. Currently this works when I invoke the script on my DB or on Postman, though when I invoke it else where it does not work.
I've looked into the post request body and 'Coordinates' is not a geography it is and encoded version (my guess), which I've tried to unpack within the query which hasn't worked. The only way I was able to unpack it within a different query was st_asgeojson and then use json_decode on the result but I want this to be done in one query.
Coordinates is passed as the following code:
"0101000020E6100000000000000040604000000000000039C0"
I want to convert this either outside the query or within it, to then get the results from my query. My PHP code is as follows:
<?php
require_once('../db.php');
$rawdata = file_get_contents("php://input");
$decoded = json_decode($rawdata, true);
$coordVar = handleCoords($decoded['event']['data']['new']['Coordinates']['coordinates']);
$res = pg_query_params($conn, 'SELECT "ShapeID" FROM "Shapes" WHERE st_within( ST_SetSRID( ST_MakePoint($1, $2), 4326), "Coordinates"::geometry) ', array($coordVar[0], $coordVar[1]));
while ($row = pg_fetch_assoc($res) ){
print_r($row['ShapeID]);
}
function handleCoords($data) {
return array($data[0], $data[1]);
}
?>
When testing my queries I obtained "Coordinates" from one of my tables which was a bytea code when looking at the results, as this is a geography data type. I got around this by using the ::geometry conversion, thinking about this, the issue I had was a simple fix. As the coordinates passed through the POST request body was also of the same data type, geography, therefore applying the same conversion would allow the query to work when invoked from any application.
The code is as follows:
<?php
require_once('../db.php');
$rawdata = file_get_contents("php://input");
$decoded = json_decode($rawdata, true);
$coordVar = handleCoords($decoded['event']['data']['new']['Coordinates']);
$res = pg_query_params($conn, 'SELECT "ShapeID" FROM "Shapes" WHERE st_within( ST_SetSRID( $1::geometry, 4326), "Coordinates"::geometry) ', array($coordVar));
while ($row = pg_fetch_assoc($res) ){
print_r($row['ShapeID]);
}
?>
Related
I'm looking to get some input on how to make modular code that performs a PHP parse_ini_file and then uses the returned values to run JSON decodes.
I have a BACnet API that returns a JSON structure for BACnet points in an automation system. I wrote the following code to decode the JSON data to return just the "present-value" field and then I display the value on a webpage.
<?php
$url = "http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "<b>Room temperature</b>: ". $json_data["present-value"]. " DEG F";
;?>
This works well but I want to make this code modular so it can be used for many other points.
I created an INI file with a list of other points and the URL that contains the JSON data from the API.
## BACnet Configuration File
# BACnet Object URLs from WACNET Browser API
[bacnet]
SEA_RMT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.0
SEA_SRV_SEA_SV1_01_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.3
SEA_SRV_SEA_SV1_02_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.4
SEA_SRV_SEA_SV1_03_EXHT = http://hostname.lcl:47800/api/v1/bacnet/devices/10100/objects/0.5
What I'd like to do is use the INI file to get the present value of each point in the list and then create a variable that is the name of the point and set it equal to the "present-value" field. Then I can reference the point using the PHP variable on the HTML page like this:
<?php echo "$SEA_SRV_SEA_SV1_01_EXHT";?>
I started with the code below but it doesn't work.
<?php
// Parse the settings file
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini');
// Parse the keys to variables and add data
foreach ($bacnetini as $key => $value) {
$url = $value;
$json = file_get_contents($url);
$json_data = json_decode($json, true);
$$key = $json_data;
}
?>
I'd love to get some other opinions on the best way to accomplish this since I don't really know where to go from here.
I've looked through these other Stack Overflow questions but I don't know how to get the pieces to all fit together.
Parsing a config file in php to variables
Get JSON object from URL
Why not try something like this instead? This will allow you to create other sections in your INI file that won't affect your script.
<?php
$bacnetini = parse_ini_file('/var/www/config/bacnet.ini', true);
$data = array();
foreach ($bacnetini['bacnet'] as $key => $url) {
$data[$key] = json_decode(file_get_contents($url), true);
}
var_dump($data['SEA_SRV_SEA_SV1_01_EXHT']);
?>
As a part of an assignment I am trying to pull some statistics from the Riot API (JSON data for League of Legends). So far I have managed to find summoner id (user id) based on summoner name, and I have filtered out the id's of said summoner's previous (20) games. However now I can't figure out how to get the right values from the JSON data. So this is when I'll show you my code I guess:
$matchIDs is an array of 20 integers (game IDs)
for ($i = 1; $i <= 1; $i++)
{
$this_match_data = get_match($matchIDs[$i], $server, $api);
$processed_data = json_decode($this_match_data, true);
var_dump($processed_data);
}
As shown above my for loop is set to one, as I'm just focusing on figuring out one before continuing with all 20. The above example is how I got the match IDs and the summoner IDs. I'll add those codes here for comparison:
for ($i = 0; $i <= 19; $i++)
{
$temp = $data['matches'][$i]['matchId'];
$matchIDs[$i] = json_decode($temp, true);
}
$data is the variable I get when I pull all the info from the JSON page, it's the same method I use to get $this_match_data in the first code block.
function match_list($summoner_id, $server, $api)
{
$summoner_enc = rawurlencode($summoner);
$summoner_lower = strtolower($summoner_enc);
$curl =curl_init('https://'.$server.'.api.pvp.net/api/lol/'.$server.'/v2.2/matchlist/by-summoner/'.$summoner_id.'?api_key='.$api.'');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);
curl_close($curl);
return $result;
}
Now to the root of the problem, This is where I put the data I get from the site, so you can see what I am working with. Now by using the following code I can get the first value in that file, the match ID.
echo $processed_data['matchId'];
But I can't seem to lock down any other information from this .json file. I've tried typing stuff like ['region'] instead of ['matchId'] with no luck as well as inserting index numbers like $processed_data[0], but nothing happens. This is just how I get the right info from the first examples and I am really lost here.
Ok, so I think I've figured it out myself. By adding this to the code I can print out the json file in a way more human-friendly way, and that should make it much easier to handle the data.
echo ("<pre>");
var_dump($processed_data);
echo ("</pre>");
Im new to php and tried to get a json object from the twitch API to retrieve one of its values and output it. i.e
i need to get the information from this link: https://api.twitch.tv/kraken/users/USERNAME/follows/channels/CHANNELSNAME
plus i need to to something so i can modify the urls USERNAME and CHANNELSUSERNAME. I want it to be a api to call for howlong user XY is following channelXY and this will be called using nightbots $customapi function.
the date i need from the json is "created_at"
Since we were able to clear out the errorsheres the final PHP file that works if anyone encounters similiar errors:
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
?>
You have a typo in your code on the first line and you're not storing the result of your json_decode anywhere.
<?php
$url = "https://api.twitch.tv/kraken/users/" . $_GET['username'] . "/follows/channels/" . $_GET['channel'];
$result = file_get_contents($url);
$result = json_decode($result, true);
echo $result["created_at"];
You have to call the page this way page.php?username=yeroise&channel=ceratia in order to output the created_at value for this user and this channel.
In your code you're using 2 different ways to get the content of the page and you only need one (either file_get_contents or using CURL), I chose file_get_contents here as the other method adds complexity for no reason in this case.
I'm using a jquery plugin called DataTables, and it requires me to return a json string in order to render the table.
Currently, the outputted json looks like this (see the aaData array):
{"sEcho":0,"aaData":[[{"ID":"1","idPatient":"122342","idFacility":"3","idTreatment":"3"}]]}
I'm wondering if the { } braces should actually be in the aaData array. In fact, I think the braces are actually what's causing the JSON parse error.
The actual code that generates this is listed below. (core->dbh is a PDO handle)
<?php
require_once('core/Core.php');
$core = Core::get_instance();
$sql = 'SELECT ID, idPatient, idFacility, idTreatment
FROM Pathology WHERE idPatient = 122342';
$stmt = $core->dbh->prepare($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
// bind parameters
$stmt->execute();
// prepare output for DataTables
$data = array("sEcho" =>intval($_GET['sEcho']),
"aaData" =>array()
);
while($result = $stmt->fetchAll()) {
$data['aaData'][] = $result;
}
echo json_encode($data);
?>
Could someone please tell me how can I remove the curly braces, or if the JSON is improperly formatted in another way that could be causing the parse error?
Thanks
The JSON is fine. You are encoding it with PHP via json_encode, that can't be the problem. My guess would be that by doing this $data['aaData'][] = $result; you are nesting twice (see the double brackets) your results and the plugin fails. Try this: $data['aaData'] = $result;
require_once 'include/BestBuy/Service/Remix.php';
$skuid = rawurldecode($_GET['skuid']);
$apiKey = 'tfvs7h89pwn4pzmyj9nxemmg'; // Your API key
$remix = new BestBuy_Service_Remix($apiKey);
$result = $remix->product('$skuid','json')
->show(array('url'))
->query();
$data = json_decode ($result, true);
$feed = $data['url'];
print <<< FEEDS
$feed
FEEDS;
When I put this script into my page, the $feed will echo the current URL.
But when I manually supply the script with an integer, replacing ($skuid) it will be successful.
It's really weird, But I think it has something to do with me using a variable in that specific array.
And it is also weird, because It was working before I re arranged some of the HTML.
I'm trying to approach this problem the most logical way.
Please help.
Thanks.
should you have $skuid in quotes? I would expect:
$result = $remix->product($skuid,'json')
rather than
$result = $remix->product('$skuid','json')