I am trying to echo out the rate but it's not showing. What is the actual reason. Can anyone help mw with it?
Here's the code
<?php
// Create the shortcode
function currency_conversion_shortcode() {
$url = "https://api.fastforex.io/convert?from=AED&to=NPR&amount=1&api_key=xxxxx-xxxx-xxxxx";// api key added on purpose
$result = file_get_contents($url);
$result = json_decode($result, true);
return $result['result'] . " NPR";
}
add_shortcode( 'currency_conversion', 'currency_conversion_shortcode' );
?>
Response data
{
"base": "AED",
"amount": 1,
"result": {
"NPR": 35.56,
"rate": 35.5597
},
"ms": 5
}
function currency_conversion_shortcode()
{
$url = "https://api.fastforex.io/convert?from=AED&to=NPR&amount=1&api_key=xxxxx-xxxx-xxxxx";
$result = file_get_contents($url);
$result = json_decode($result, true);
return $result['result']['rate'] . " NPR";
}
add_shortcode('currency_conversion', 'currency_conversion_shortcode');
Related
I'm trying to edit a JSON file using php, I've set up a little ReactJS app has form elements.
My JSON is as follows
[
{
"id": 1,
"Client": "client 1",
"Project": "project 1",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-1"
},
{
"id": 2,
"Client": "client 2",
"Project": "project 2",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-2"
},
{
"id": 3,
"Client": "client 3",
"Project": "project 3",
"StartDate": "2018\/11\/02 16:57:35",
"CompletedDate": "",
"projectUrl": "project-3"
}
]
So far i have code to create a new "project" at the end of the file. My PHP is as follows
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$clientName = $_POST['clientName'];
$ProjectName = $_POST['projectName'];
$url = strtolower($_POST['url']);
$date = date('Y/m/d H:i:s');
$message = "";
$url = '../json/projects.json';
if( file_exists($url) )
if(file_exists('../json/projects.json'))
{
$current_data = file_get_contents('../json/projects.json');
$array_data = json_decode($current_data, true);
$extra = array(
'id' => count($array_data) + 1,
'Client' => $clientName,
'Project' => $ProjectName,
'StartDate' => $date,
'CompletedDate' => "",
'projectUrl' => $projectFileName + ".json"
);
$array_data[] = $extra;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents('../json/projects.json', $final_data))
{
$message = "sent";
}
else
{
$message = "notSent";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
What i can figure out is how to edit lets say "CompletedDate" value to todays date with a click of the button.
I have an hidden input field on my page that has the project ID in, so what I'm after is helping getting that id, matching it to the JSON, then editing the completed date that matches the ID.
This PHP will fire using ajax so i can pass the ID pretty easy.
Using similar code to what you already use, you can update the relevant data by using the ID as the index into the decoded JSON file. As ID 1 will be the [0] element of the array, update the [$id-1] element with the date...
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
try {
$id = 2; // Fetch as appropriate
$date = date('Y/m/d H:i:s');
$url = '../json/projects.json';
if( file_exists($url) )
{
$current_data = file_get_contents($url);
$array_data = json_decode($current_data, true);
$array_data[$id-1]['CompletedDate'] = $date;
$final_data = json_encode($array_data, JSON_PRETTY_PRINT);
if(file_put_contents($url, $final_data))
{
$message = "updated";
}
else
{
$message = "notUpdated";
}
}
else
{
$message = "jsonFileNotFound";
}
$response = $message;
} catch (Exception $e) {
$response = $e->getMessage();
}
echo $response;
}
You may need to tweak some of the bits - especially how the ID is picked up ($_GET?) and any messages you want.
I've also updated the code to make more consistent use of $url as opposed to hard coding it in a few places.
I am trying to find out whether a user is part of a Steam group. To do this, I'm using Steam's Web API, and using URL:
https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE
To get a JSON response of all groups that a user is part of.
Now I want to find out if they're part of my specific group with ID: 1111111 using PHP.
How would one do that? Currently I have the code being decoded like so:
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
This makes the $pretty variable contain the entire JSON response.
How would I use PHP to find the group ID in a response that looked like this?
{
"response": {
"success": true,
"groups": [
{
"gid": "4458711"
},
{
"gid": "9538146"
},
{
"gid": "11683421"
},
{
"gid": "24781197"
},
{
"gid": "25160263"
},
{
"gid": "26301716"
},
{
"gid": "29202157"
},
{
"gid": "1111111"
}
]
}
}
Can't figure it out.
Any help? :)
Use the below code to check whether user is exist in the response or not
$groupid = "1111111";
$is_exists = false;
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList/v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result, true);
foreach ($pretty['response']['groups'] as $key => $value) {
if($value['gid'] == $groupid) {
$is_exists = true;
break;
}
}
// check is_exists
Check that above variable $is_exists for true or false
$groupid = "1111111";
$url = "https://api.steampowered.com/ISteamUser/GetUserGroupList /v1/?key=APIKEYHERE&steamid=STEAMID64HERE";
$result = file_get_contents($url);
// Will dump a beauty json :)
$pretty = json_decode($result);
$s = $pretty->response->groups;
foreach($s as $value)
{
if((int) $groupid == $value->gid)
{
echo "Found";
}else
{
echo "Not found";
}
}
i created an API
this is URL http://geoip.mediaciptainformasi.co.id/ip.php?ip=1.1.1.1
and the output is in json response like this
{
"ip_address": "1.1.1.1",
"Jumlah Akses per hari": "1 kali",
"ip_from": "16843008",
"ip_to": "16843263",
"country_code": "AU",
"country_name": "Australia",
"region_name": "Queensland",
"city_name": "Brisbane",
"latitude": "-27.46794",
"longitude": "153.02809",
"zip_code": "4000",
"time_zone": "+10:00"
}
how can i get the specific key value, like country_name and city_name for other website?
I've tried this on localhost but doesn't work
<?php
$url = "http://geoip.mediaciptainformasi.co.id/ip.php/?ip=110.138.84.204";
$jsondata = file_get_contents($url);
$obj = json_decode($jsondata);
echo $obj->latitude;
echo $obj->country_name;
?>
Using cURL:
<?php
// when you want to display errors by overriding `php.ini`
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// function to return cURL response
function get_data_function($ip)
{
if ($ip == NULL){
$ip = "1.1.1.1";
}
// base url
$url = "http://geoip.mediaciptainformasi.co.id/ip.php/?ip=".$ip;
$ch = curl_init($url);
// cURL OPTIONS:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
// Check for errors and display the error message
if($errno = curl_errno($ch)) {
$error_message = curl_strerror($errno);
echo "cURL error ({$errno}):\n {$error_message}";
}
if (isset($result)) {
$response = json_decode($result, true);
}
curl_close($ch);
return $response;
}
// calling method with desired IP string
$response = get_data_function("110.138.84.204");
// get specific value by its json key
echo "Country Name " . $response['country_name'];
echo "</br>";
echo "City Name " . $response['city_name'];
echo "</br>";
echo "</br>";
// in case of view full response
var_dump($response);
?>
Works fine on localhost
$url = "http://geoip.mediaciptainformasi.co.id/ip.php/?ip=110.138.84.204";
$jsondata = file_get_contents($url);
$obj = json_decode($jsondata);
// Use this to see object, after that you can do what you want to $obj
print_r($obj);
I'm editing file php for telegram bot. When I test on telegram, it shows no response at all. On PHP command line, it said:
Warning:
file_get_contents(https://api.telegram.org/bottoken/sendMessage):
failed to open
stream: HTTP request failed! HTTP/1.1 400 Bad Request in G:\xampp\htdocs\xbot\file.php on
line 39
And on line 39:
$result = file_get_contents(request_url('sendMessage'), false, $context);
But, it works when I change function create_response to this:
function create_response($text)
{
$conn = mysqli_connect("localhost","root","admintma","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
//$hasil = '';
if (mysqli_num_rows($cari) > 0) {
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"]. ": " . $row["ayattext"]. ". ";
var_dump($hasil);
}
} else {
$hasil = "0 results";
}
return $hasil;
mysqli_close($conn);
}
But it only shows just last result while on php command line show complete result:
string(157) "Value1"
string(219) "Value2"
string(462) "Value3"
string(555) "Value4"
string(246) "Value5"
{
"ok": true,
"result": {
"message_id": 197,
"from": {
"id": 107653xxx,
"first_name": "x_bot",
"username": "x_bot"
},
"chat": {
"id": 2887198,
"first_name": "xxx",
"username": "xxx"
},
"date": 1437240345,
"reply_to_message": {
"message_id": 196,
"from": {
"id": 2887xxx,
"first_name": "xxx",
"username": "xxx"
},
"chat": {
"id": 2887xxx,
"first_name": "xxx",
"username": "xxx"
},
"date": 1437240342,
"text": "mengetahuinya"
},
"text": "Value5"
}
}
I'm confused, how to solve this problem? Thanks in advance.
Here's the complete code:
<?php
include("token.php");
//include("db.php");
function request_url($method)
{
global $TOKEN;
return "https://api.telegram.org/bot" . $TOKEN . "/". $method;
}
function get_updates($offset)
{
$url = request_url("getUpdates")."?offset=".$offset;
$resp = file_get_contents($url);
$result = json_decode($resp, true);
if ($result["ok"]==1)
return $result["result"];
return array();
}
function send_reply($chatid, $msgid, $text)
{
$data = array(
'chat_id' => $chatid,
'text' => $text,
'reply_to_message_id' => $msgid
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
$context = stream_context_create($options);
$result = file_get_contents(request_url('sendMessage'), false, $context);
print_r($result);
}
function create_response($text)
{
$conn = mysqli_connect("localhost","root","xxx","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
//$hasil = '';
if (mysqli_num_rows($cari) > 0) {
$hasil = array();
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"] . ": " . $row["ayattext"] . ". ";
//var_dump($hasil);
}
} else {
$hasil = "0 results";
}
return $hasil;
mysqli_close($conn);
}
function process_message($message)
{
$updateid = $message["update_id"];
$message_data = $message["message"];
if (isset($message_data["text"])) {
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$response = create_response($text);
send_reply($chatid, $message_id, $response);
}
return $updateid;
}
function process_one()
{
$update_id = 0;
if (file_exists("last_update_id")) {
$update_id = (int)file_get_contents("last_update_id");
}
$updates = get_updates($update_id);
foreach ($updates as $message)
{
$update_id = process_message($message);
}
file_put_contents("last_update_id", $update_id + 1);
}
while (true) {
process_one();
}
?>
The problem is that your function process_message() expects create_response() to return a string, and the code that doesn't work is returning an array when there are results and a string when there are no results. It's best if it returns always the same type of data.
To fix it, change the create_response() function to always return an array, and have process_message() to use it however it needs, i.e., transform it in a string.
By the way, your return command must be the last command executed in the function. You have mysqli_close($conn); after it, which is never executed if return is above it.
So, those two functions become:
function create_response($text)
{
$conn = mysqli_connect("localhost","root","xxx","aq");
$data = array();
$sql = "Select s.text_sr AS surat, s.no_sr AS nosurat, qi.verseid AS ayat, " .
"qi.ayahtext AS ayattext from quranindonesia qi left join surah s on " .
"qi.suraid=s.no_sr where qi.ayahtext like '%$text%' limit 3,5";
$cari = mysqli_query($conn, $sql);
$hasil = array();
if (mysqli_num_rows($cari) > 0) {
// output data of each row
while($row = mysqli_fetch_array($cari)) {
$hasil[] = "QS.[".$row["surat"]."-" . $row["nosurat"]. "]:" .
$row["ayat"] . ": " . $row["ayattext"] . ". ";
}
}
mysqli_close($conn);
return $hasil;
}
function process_message($message)
{
$updateid = $message["update_id"];
$message_data = $message["message"];
if (isset($message_data["text"])) {
$chatid = $message_data["chat"]["id"];
$message_id = $message_data["message_id"];
$text = $message_data["text"];
$responseArr = create_response($text);
if (count($responseArr) > 0) {
$response = implode(". ", $responseArr) . ".";
} else {
$response = "0 results";
}
send_reply($chatid, $message_id, $response);
}
return $updateid;
}
here is my sample code. my developer mode is already enabled but there is no menu tabs options.
you can also add me on wechat so I can elaborate my problems in this matter, here is my wechat ID VinceZen. I badly need some help guys. Thank you in advance.
<?php
$data[] = '772134292672v';
$data[] = $_GET['timestamp'];
$data[] = $_GET['nonce'];
asort($data);
$strData = '';
$d = '';
$authString = '';
foreach($data as $d)
{
$authString .= $d;
}
//verify the signature
if(sha1($authString) == $_GET['signature'])
{
//check the echostr
if(!empty($_GET['echostr']))
{
echo $_GET['echostr'];
die();
}
else
{
//logic
//Getting access_token from customize menus
static function get_access_token($appid,$secret){
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$json=http_request_json($url);//here cannot use file_get_contents
$data=json_decode($json,true);
if($data['access_token']){
return $data['access_token'];
}else{
return "Error occurred while geting the access_token";
}
}
//Though URL request is https',cannot use file_get_contents.Using CURL while asking the JSON data
function http_request_json($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
$return = "<xml>
<ToUserName><![CDATA['.$toUser.']]</ToUserName>
<FromUserName><![CDATA['.$fromUser.']]</FromUserName>
<CreateTime>'.time.'</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA['.text.']]</Content>
<FuncFlag>0</FuncFlag>
</xml>";
echo $return;
{
"button":[
{
"type":"click",
"name":"Daily Song",
"key":"V1001_TODAY_MUSIC"
},
{
"type":"click",
"name":" Artist Profile",
"key":"V1001_TODAY_SINGER"
},
{
"name":"Menu",
"sub_button":[
{
"type":"view",
"name":"Search",
"url":"http://www.soso.com/"
},
{
"type":"view",
"name":"Video",
"url":"http://v.qq.com/"
},
{
"type":"click",
"name":"Like us",
"key":"V1001_GOOD"
}]
}]
}
}
}
else
{
die('Access Denied');
}`enter code here`
?>