I'm working on a project and trying to find a way to add my api results to mysql.
Here is the page were you can find the results.
Here is the code of the page:
<?php
///PLOT PROJECT USER REQUEST
//HELPER FUNCTION TO PRINT TO CONSOLE
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//PLOT PROJECT REQUEST
$appId = '9fed0c75ca624e86a411b48ab27b3d5a';
$private_token = 'VGjPehPNBa5henSa';
$qry_str = "/api/v1/account/";
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
$geofenceId = '736cb24a1dae442e943f2edcf353ccc7';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com/api/v1/notification/?geofenceId=' . $geofenceId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
?>
You can use json_decode() to decode your JSON string and take the values that you need to make your query. Read more at:
http://php.net/manual/en/function.json-decode.php
<?php
//The response from http://www.jobsinsac.com/api/api_notification.php
$json = '{ "success": true, "result": { "data": [{ "placeId": "736cb24a1dae442e943f2edcf353ccc7", "cooldownDays": 0, "triggerTimes": "inherit", "state": "published", "cooldownSeconds": 1, "data": "http://www.illuminatimc.com", "enabled": true, "geofenceId": "736cb24a1dae442e943f2edcf353ccc7", "id": "0cad6b54d225459e85cd8c27567f8b0b", "message": "Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.", "created": "2015-03-17T18:54:41Z", "timespans": [], "handlerType": "landingPage", "trigger": "enter" }], "total": 1 } }';
$data = json_decode($json, true);
print_r($data);
?>
Output:
Array
(
[success] => 1
[result] => Array
(
[data] => Array
(
[0] => Array
(
[placeId] => 736cb24a1dae442e943f2edcf353ccc7
[cooldownDays] => 0
[triggerTimes] => inherit
[state] => published
[cooldownSeconds] => 1
[data] => http://www.illuminatimc.com
[enabled] => 1
[geofenceId] => 736cb24a1dae442e943f2edcf353ccc7
[id] => 0cad6b54d225459e85cd8c27567f8b0b
[message] => Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.
[created] => 2015-03-17T18:54:41Z
[timespans] => Array
(
)
[handlerType] => landingPage
[trigger] => enter
)
)
[total] => 1
)
)
Related
I'm using a cURL request to grab data from a website and adding them to properties within a loop later. However, I'm stuck on making the data adjustable enough where I can add them directly within the objects.
I have a cURL request that I'm calling that grabbing all the content that I need as below:
public function request()
{
$resource = curl_init();
curl_setopt(
$resource,
CURLOPT_URL,
'lorem ipsum'
);
curl_setopt(
$resource,
CURLOPT_HTTPHEADER,
['API Auth']
);
curl_setopt(
$resource,
CURLOPT_REFERER,
'http://' . $_SERVER['SERVER_NAME'] . '/'
);
curl_setopt(
$resource,
CURLOPT_USERAGENT,
'F'
);
curl_setopt(
$resource,
CURLOPT_RETURNTRANSFER,
1
);
$response = json_decode(curl_exec($resource), true);
if (!curl_errno($resource)) {
$info = curl_getinfo($resource);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
};
return $response;
}
When I call the following execution $offices_array = $this->request(); print_r2($offices_array);, this is the return that I receive:
Array
(
[paginator] => Array
(
[total] => 131
[per_page] => 500
[current_page] => 1
[last_page] => 1
[prev_page] =>
[next_page] =>
)
[data] => Array
(
[0] => Array
(
[id] => 1
[name] => Atlanta
)
I'm using this function _csv_to_array:
private function _csv_to_array($filepath) {
$data_array = array();
if(is_readable($filepath)) {
$fp = fopen($filepath, 'r');
while(($data_item = fgetcsv($fp, 1000, "\t")) !== false) {
$data_array[] = array_map('utf8_encode', $data_item);
}
fclose($fp);
}
return $data_array;
}
to print out data as this:
Array
(
[0] => Array
(
[0] => ABU DHABI
[1] => FHI
)
How could I do something similar with the cURL request?
I want to know how to get WHMCS Price via WHMCS API.
I have created a little script to get price via API which is working fine but when I update the script on my external WHMCS pages it is taking a lot more time to update the function on each page my simple question is to get price via API without defining the first array see example below.
Array
(
[result] => success
[totalresults] => xxx
[products] => Array
(
[product] => Array
(
[0] => Array // how can I call it dynamically
(
[pid] => 1
[gid] => 1
[type] => hostingaccount
[name] => Plan Name
[description] => Plan Description
[module] => cpanel
[paytype] => recurring
[pricing] => Array
(
[USD] => Array
(
[prefix] => $
[suffix] => USD
[msetupfee] => 0.00
[qsetupfee] => 0.00
[ssetupfee] => 0.00
[asetupfee] => 0.00
[bsetupfee] => 0.00
[tsetupfee] => 0.00
[monthly] => 0.14
[quarterly] => 0.39
[semiannually] => 0.73
[annually] => 1.32
[biennially] => 2.39
[triennially] => 3.20
)
)
)
)
)
)
I just want to get price after I define [pid] and then I will create a function like
GetPrice($pid, $billingcycle); // to get produce price according to tenure
My Script:
$identifier = "IDENTIFIER";
$secret = "SECRET";
$APIURL = "mydomain/whmcs_directory/includes/api.php"; // it is with HTTPS
$postfields = array(
'username' => $identifier,
'password' => $secret,
'action' => 'GetProducts',
'responsetype' => 'json',
);
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APIURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
and then I want to use function to get price according product id & tenure as defined earlier but complete function looks like this.
function GetPrice($pid, $billingcycle){
// $pid will be product ID
// $billingcycle will be 1,3,6,12,24,36 accordingly.
/**
* It would be great if I could just remove "["products"]["product"]"
* But I understand to call API I have define them so it's Okay.
*/
$monthly = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["monthly"];
$quarterly = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["quarterly"];
$semiannually = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["semiannually"];
$annually = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["annually"];
$biennially = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["biennially"];
$triennially = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["triennially"];
if( $billingcycle == "1" ){
echo $monthly;
}
if( $billingcycle == "3" ){
echo $quarterly;
}
if( $billingcycle == "6" ){
echo $semiannually;
}
if( $billingcycle == "12" ){
echo $annually;
}
if( $billingcycle == "24" ){
echo $biennially;
}
if( $billingcycle == "36" ){
echo $triennially;
}
}
I got help from WHMCS API Reference
This has done with php, please improve my code if require.
I have achieved this with the following code which work dynamically and works with product id.
PHP Function
function GetPrice($product_id, $billingcycle){
$identifier = "WHMCS_IDENTIFIER";
$secret = "WHMCS_SECRET";
$APIURL = "YOURDOMAIN.com/WHMCS_DIRECTORY/includes/api.php"; // use HTTPS
$postfields = array(
'username' => $identifier,
'password' => $secret,
'action' => 'GetProducts',
'pid' => $product_id, // Product id
'responsetype' => 'json',
);
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APIURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); // SET to 0 for non SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
//die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
die("Out of Stock");
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
$monthly = $jsonData["products"]["product"][0]["pricing"]["USD"]["monthly"];
$quarterly = $jsonData["products"]["product"][0]["pricing"]["USD"]["quarterly"];
$semiannually = $jsonData["products"]["product"][0]["pricing"]["USD"]["semiannually"];
$annually = $jsonData["products"]["product"][0]["pricing"]["USD"]["annually"];
$biennially = $jsonData["products"]["product"][0]["pricing"]["USD"]["biennially"];
$triennially = $jsonData["products"]["product"][0]["pricing"]["USD"]["triennially"];
if( $billingcycle == "1" ){
echo round( str_replace('.00', '', $monthly), 2 );
}
if( $billingcycle == "3" ){
echo round( str_replace('.00', '', $quarterly) / 3, 2 );
}
if( $billingcycle == "6" ){
echo round( str_replace('.00', '', $semiannually) / 6, 2 );
}
if( $billingcycle == "12" ){
echo round( str_replace('.00', '', $annually) / 12, 2 );
}
if( $billingcycle == "24" ){
echo round( str_replace('.00', '', $biennially) / 24, 2 );
}
if( $billingcycle == "36" ){
echo round( str_replace('.00', '', $triennially) / 36, 2 );
}
}
Using Function
echo GetPrice( 1 , 1 );
Output
1.99
Trying to echo a couple of values from the CURL JSON response so i can put them in to a foreach loop but i can only get single indexed values to work.
$request = curl_init($api); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
//curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded"
));
$response = (string)curl_exec($request); // execute curl fetch and store results in $response
curl_close($request); // close curl object
$result = json_decode($response, true); // true turns it into an array
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
echo 'Last Name: ' . $result[0]['last_name'] . '<br />'; // yet i can return the first value
Example Array output
Array
(
[0] => Array
(
[id] => 34761
[first_name] => A
[last_name] => Bailes
[clinic] =>
[phone] => 7409923279
[fax] => 7409926740
[address1] => 507 Mulberry Heights Rd
[address2] =>
[city] => Pomeroy
[subdivision] => OH
[country_code] =>
[postal_code] => 45769-9573
[timezone] => Array
(
[timezone_type] => 3
[timezone] => America/New_York
)
[state] => OH
)
)
I have json decode set to true for array output
$result = json_decode($response, true); // true turns it into an array
but when i try to echo the 'first_name' values it just returns empty.
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
Yet i can return an indexed value
echo 'First Name: ' . $result[0]['first_name'] . '<br />';
What am i doing wrong here?
Your result array is nested 2 deep. $result is an array of arrays. So:
$result[0]['first_name']
or
foreach ($result as $r) {
echo $r['first_name'];
}
Response depend on server answer your request, the following work perfect to extract access token for example, you can try the following steps to test what you have and extract what you need too
After
$response = curl_exec($ch);
curl_close($ch);
I start to show what I get by
Test:
print_r ($response);
Then go to extract (where server response ) header and body to use what available in each of them
list($header, $body) = explode("\r\n\r\n", $response, 2);
Test:
echo $header;
echo $body;
then I’m extract item in $body to use in my code using stdClass
$bodyObject = json_decode($body);
Test:
print_r($bodyObject);
Test:
echo $bodyObject->access_token;
I need to interpret the array received from a remote licensing.
I am calling the remote api via curl and the answer in the browser is:
The parsed answer from curl done by using:
parse_str(curl_exec($ch), $parsed);
print_r($parsed);
is exactly as here:
Array ( [{"success":true,"uses":154,"purchase":{"id":"GYFt6sW7hbURSVdSpipb5g] => =","created_at":"2015-06-06T16:44:41Z","email":"askolon11#gmail.com","full_name":"daniel","variants":"","custom_fields":[],"product_name":"Direkt 1.2","subscription_cancelled_at":null,"subscription_failed_at":null}} )
I tried already for several hours to get the "success" item so later on to check it if it is true or false.
I used
while (list($var, $val) = each($parsed)) {
print "$var is $val\n";
}
but the result is the same.
Also I tried:
$parsed[0]['success'] or $parsed[0]['success']
and no result as well.
My full code is:
<?php $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.gumroad.com/v2/licenses/verify");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, true);
$data = array( 'product_permalink' => 'skQsA', 'license_key' => 'AB26AD9D-1B3B42E0-92356540-CF4E7C1B' );
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
$info = curl_getinfo($ch);
$output = array();
parse_str(curl_exec($ch), $parsed);
print_r($parsed); // HERE WE HAVE THE ARRAY
while (list($var, $val) = each($parsed)) {
// print "$var is $val\n";
}
curl_close($ch);
?>
Thank you.
The API seems to return a JSON encoded string. So instead of:
parse_str(curl_exec($ch), $parsed);
use:
$parsed = json_decode(curl_exec($ch), true);
Then a print_r($parsed) will output:
Array
(
[success] => 1
[uses] => 154
...
)
And for checking success value:
if ($parsed['success']) {
// Do stuff
}
Instead of doing
$parsed[0]['success'];
try just
$parsed['success'];
If the array you are getting back is an associative array, then the 'key' will be the word 'success'.
$parsed = [
"success" => true,
"uses" => 154,
"purchase" =>
[
"id" => "GYFt6sW7hbURSVdSpipb5g] => =",
"created_at" => "2015-06-06T16:44:41Z",
"email" => "askolon11#gmail.com",
"full_name" => "daniel",
"variants" => "",
"custom_fields" => [],
"product_name" => "Direkt 1.2",
"subscription_cancelled_at" => null,
"subscription_failed_at" => null
]];
if($parsed['success'])
echo 'true';
else
echo 'false';
I have the following text that I want to strip out and grab the data.
(function() {})({
"Data": {
"Status": "SUCCESS",
"Name": "Facebook Inc",
"Symbol": "FB",
"LastPrice": 31.91,
"Change": -1.12,
"ChangePercent": -3.39085679685135,
"Timestamp": "Fri May 25 16:00:05 UTC-04:00 2012",
"MarketCap": 20214729720,
"Volume": 37189630,
"ChangeYTD": 0,
"ChangePercentYTD": 0,
"High": 32.95,
"Low": 31.11,
"Open": 32.9
}
})
I also have the following code that IS working with google api which will be leaving us in October this year.
<?php
//Obtain Quote Info
$quote = file_get_contents('http://finance.google.com/finance/info?client=ig&q=NASDAQ:' . $stock . '');
//Remove CR's from ouput - make it one line
$json = str_replace("\n", "", $quote);
//Remove //, [ and ] to build qualified string
$data = substr($json, 4, strlen($json) -5);
//decode JSON data
$json_output = json_decode(utf8_decode($data));
// get the last price
$perc = $json_output->c;
$last = $json_output->l;
$date = $json_output->lt;
$name = $json_output->t;
?>
For whatever reason I cannot figure out how to get the other to work with my code. Anyone have any suggestions?
Just use http://dev.markitondemand.com/Api/Quote/json?symbol=AAPL as the url, leaving out the p in json.
<?php
$stock = "FB";
//Obtain Quote Info
//$quote = file_get_contents('http://dev.markitondemand.com/Api/Quote/json?symbol='.$stock);
//or with curl
$quote = curl_get('http://dev.markitondemand.com/Api/Quote/json?symbol='.$stock);
function curl_get($url){
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/1.0");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
//decode JSON data
$json_output = json_decode(utf8_decode($quote));
$perc = $json_output->Data->ChangePercent;
$last = $json_output->Data->LastPrice;
$date = $json_output->Data->Timestamp;
$name = $json_output->Data->Name;
print_r($json_output);
/*
stdClass Object
(
[Data] => stdClass Object
(
[Status] => SUCCESS
[Name] => Facebook Inc
[Symbol] => FB
[LastPrice] => 31.91
[Change] => -1.12
[ChangePercent] => -3.3908567968514
[Timestamp] => Fri May 25 16:00:05 UTC-04:00 2012
[MarketCap] => 20214729720
[Volume] => 37189630
[ChangeYTD] => 0
[ChangePercentYTD] => 0
[High] => 32.95
[Low] => 31.11
[Open] => 32.9
)
)*/
?>
The code you are using for Google Finance is directly customized to work with the output from the Google Finance API you're using.
Here is the output from Google Finance:
// [
{
"id": "296878244325128"
,"t" : "FB"
,"e" : "NASDAQ"
,"l" : "31.91"
,"l_cur" : "31.91"
,"s": "0"
,"ltt":"4:00PM EDT"
,"lt" : "May 25, 4:00PM EDT"
,"c" : "-1.12"
,"cp" : "-3.39"
,"ccol" : "chr"
}
]
The part of your code that does:
$data = substr($json, 4, strlen($json) -5);
is exactly stripping out the unwanted characters from the GF output. For your new output wrapped inside the anonymous function, I suggest the following:
<?php
preg_match('/\(function\(\) \{\}\)\((.*)\)/', $input_string, $matches);
$data_json = $matches[1];
$json_output = json_decode($data_json, true); //true = assoc array
$final_json = $json_output['Data'];
This will assign a valid json string to the $json variable, where $input_string is the input you listed in your question. And $final_json will contain whatever is inside the Data: property of the original json.