extract value of specific key in json response from GET URL - php

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);

Related

Accessing object returned from GraphQL using curl

I have returned data using GraphQL / curl that looks like this:
{
"data" : {
"publisher" : {
"contracts" : {
"totalCount" : 11,
"count" : 1,
"resultList" : [
I want to get the resultList array and keep getting an error 'Warning: Attempt to read property "data" on string' when trying to do $result->data to move into the first object. What am I doing wrong?
My variable from the curl request is $result.
Update: I HAVE TRIED DECODING AND THE RETURNED DATA IS OF TYPE INT? How?
function getData($data_String){
$endpoint = "https://programs.api.cj.com/query";
$authToken = "pass";
$qry = '{"query":"{ publisher { contracts(publisherId: \"xxxxxxx\", limit: 1, filters: {advertiserId: \"'.$advertiser_id.'\"}) { totalCount count resultList { startTime endTime status advertiserId programTerms { id name specialTerms { name body } isDefault actionTerms { id actionTracker { id name description type } lockingMethod { type durationInDays } performanceIncentives { threshold { type value } reward { type commissionType value } currency } commissions { rank situation { id name } itemList { id name } promotionalProperties { id name } rate { type value currency } } } } } } } }","variables":null}';
$headers = array();
$headers[] = 'Content-Type: application/json';
$headers[] = 'Authorization: Bearer '.$authToken;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $endpoint);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POSTFIELDS, $qry);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
curl_close($ch);
$data = json_decode($result);
return $data;
}
First, be sure to check if the result is a valid json.
Then use json_decode to get an object
$result = json_decode($result);
if (is_object($result)) {
if (!empty($result->data->publisher->contracts->resultList)) {
$resultList = $result->data->publisher->contracts->resultList;
}
} else {
// Log or something
error_log("json decode return: " . print_r($result, true))
}

rate not showing in WordPress

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');

PHP Curl result giving trouble?

I am working with NCBI Blast api. I created logic to get result in xml format but result is comming in html format and this result again going back to redirect to display xml format. when i check original url in browser it shows direct xml data. Can any one give me solutions.
Visit this url you can find my problem peerscientist.net. This is the code.
class BlastAPI{
public function blastdata(){
$url = "https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Put&QUERY=SSWWAHVEMGPPDPILGVTEAYKRDTNSKK&PROGRAM=blastp&FILTER=L&DATABASE=nr&FORMAT_TYPE=XML";
$ncontent = $this->rid($url);
echo '<br/>RID :'.$ncontent.'<br/>';
$geturl = $this->geturl($ncontent);
echo $geturl;
$fulldata = $this->getfullData($geturl);
if($fulldata != ''){
echo '<pre>';
var_dump($fulldata);
echo '</pre>';
}else{
echo "Code Once";
}
}
public function rid($url){
$surl = $url;
echo $surl;
//header('Content-type: text/html');
$content = file_get_contents($surl);
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHtml($content);
libxml_use_internal_errors(false);
$data = $doc->getElementById("rid");
$rid = $data->getAttribute('value');
return $rid;
}
public function geturl($rid){
$srid = $rid;
$mainurl = "https://blast.ncbi.nlm.nih.gov/Blast.cgi?CMD=Get&RID=$srid&FORMAT_TYPE=XML&DESCRIPTIONS=200&ALIGNMENTS=200&NOHEADER=true";
return $mainurl;
}
public function getfullData($url){
$murl = $url;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $murl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$str = curl_exec($curl);
curl_close($curl);
if ($str === FALSE) {
echo "cURL Error: " . curl_error($curl);
}
return $str;
}
}
$nblast = new BlastAPI();
$nblast->blastdata();

How to develop user defined menu on wechat

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`
?>

Error Handling with LastFM API and simplexml_load_file

I'm using simplexml_load_file to pull album information from the LastFM API and having no problems when the requested album matches.
However, when the album is not found, LastFM returns an error, which causes the code below to output a "failed to open stream" error.
I can see that LastFM is giving me exactly what I need, but am unsure how to proceed. What is the proper way to update the code so that this error/error code is correctly handled?
Code:
$feed = simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect);
$albums = $feed->album;
foreach($albums as $album) {
$name = $album->name;
$img = $album->children();
$img_big = $img->image[4];
$img_small = $img->image[2];
$releasedate = $album->releasedate;
$newdate = date("F j, Y", strtotime($releasedate));
if ($img == "") {
$img = $emptyart; }
}
?>
if ($headers[0] == 'HTTP/1.0 400 Bad Request') {
$img_big = $emptyart;
$img_small = $emptyart;
}
That will break with a 403 error ...
Method 1 (not practical):
Basically you can mute the error with # and check if your $feed is empty. In that case, "some error" has happened, either an error with your url or a status failed from last.fm.
$feed = #simplexml_load_file("http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect);
if ($feed)
{
// fetch the album info
}
else
{
echo "No results found.";
}
In both ways, you get no results so you can probably satisfy your needs and showing "No results found" instead of showing him "Last.fm error status code, etc.."
Method 2 (recommended) - Use curl:
function load_file_from_url($url) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_REFERER, 'http://www.test.com/');
$str = curl_exec($curl);
if(str === false)
{
echo 'Error loading feed, please try again later.';
}
curl_close($curl);
return $str;
}
function load_xml_from_url($url) {
return #simplexml_load_string(load_file_from_url($url));
}
function getFeed($feedURL)
{
$feed = load_xml_from_url($feedURL);
if ($feed)
{
if ($feed['status'] == "failed")
{
echo "FAIL";
}
else
{
echo "WIN";
}
}
else {echo "Last.fm error";}
}
/* Example:
Album: Heritage
Artist: Opeth
*/
$url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=273f3dc84c2d55501f3dc25a3d61eb39&artist=opeth&album=hwwXCvuiweitage&autocorrect=0";
$feed = getFeed ($url);
// will echo FAIL
$url2 = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=273f3dc84c2d55501f3dc25a3d61eb39&artist=opeth&album=heritage&autocorrect=0";
$feed2 = getFeed ($url2);
// will echo WIN
Wouldn't it be better to first get the url, check if it doesn't contain the error, and then use simplexml_load_string instead?
Working along the lines of evaluating the state of the URL prior to passing it to simplexml_load_file, I tried get_headers, and that, coupled with an if/else statement, seems to have gotten things working.
$url = "http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=".$apikey."&artist=".$artist."&album=".$album."&autocorrect=".$autocorrect;
$headers = get_headers($url, 1);
if ($headers[0] == 'HTTP/1.0 400 Bad Request') {
$img_big = $emptyart;
$img_small = $emptyart;
}
else {
$feed = simplexml_load_file($url);
$albums = $feed->album;
foreach($albums as $album) {
$name = $album->name;
$img = $album->children();
$img_big = $img->image[4];
$img_small = $img->image[2];
$releasedate = $album->releasedate;
$newdate = date("F j, Y", strtotime($releasedate));
if ($img == "") {
$img_big = $emptyart;
$img_small = $emptyart;
}
}
}

Categories