I'm trying to pull one single property from the CREA Data Distribution Facility by it's listing ID. The purpose is for a wordpress plugin where the realtor will simply input his listing ID and it will pull all the data into the wordpress post.
If you've had any experience with this system, i'm using PHPRETS and am having a hell of time navigating through the documentation for querying. I've got a feed all setup and pulling random properties, but i'm looking to pull one specific one.
Thanks! Let me know if you need any more info.
If you looking for the php eneral code, please try this :
1- dowload PHRets_CREA.php file from CREA website : https://support.crea.ca/DDF#/discussion/20/crea-data-distribution-code-sample-in-php.
2- create your php file in the same folder :
Of course you must have $ListingKey, change it on the code
/* RETS Variables */
require("PHRets_CREA.php");
$RETS = new PHRets();
$RETSURL = "http://data.crea.ca/Login.svc/Login";
$RETSUsername = "Username";
$RETSPassword = "Password";
$RETS->Connect($RETSURL, $RETSUsername, $RETSPassword);
$RETS->AddHeader("RETS-Version", "RETS/1.7.2");
$RETS->AddHeader('Accept', '/');
$RETS->SetParam('compression_enabled', true);
$RETS_LimitPerQuery = 10;
$TimeBackPull = "-1 hours";
echo 'Connecting to RETS as : <span style="color:#008000;"><b>'.$RETSUsername.'</b></span><br/>';
echo "-----GETTING ALL Listings-----<br/>";
//Get Id's
$DBML = "(LastUpdated=" . date('Y-m-d', strtotime($TimeBackPull)) . ")";
$params = array("Limit" => 1, "Format" => "STANDARD-XML", "Count" => 1);
$results = $RETS->SearchQuery("Property", "Property", $DBML, $params);
$totalAvailable = $results["Count"];
echo "-----".$totalAvailable." Found-----<br/>";
$ListingKey = "ListingKey here";
$propriety = $RETS->SearchQuery("Property", "Property", "(ID=".$ListingKey.")", array("Limit" => 1, "Format" => "STANDARD-XML"));
echo "<pre>";
print_r($propriety);
echo "</pre>";
Related
I'm using the Google Sheets API to write some data into the sheets, but so far either I clear it all and write everything again or I write in new rows (which Sheets API does by default).
I am now writing a single column per run, but I need to get the first available column in the sheet, so I can pass it as the range of writing.
This is my code so far:
$sheet = new \Google_Service_Sheets($this->client);
$range = "'" . $sheetName . "'!" . $rangeArg . (strlen($rangeArg) == 2 ? '' : count($data) + 1000);
$response = $sheet->spreadsheets_values->get($this->sheetId, $range);
if (!$clear && $response && $response->values) {
$c = count($response->values);
$newRange = (intval(substr($rangeArg, 1, 1)) + $c);
$newRange = substr($rangeArg, 0, 1) . $newRange . substr($rangeArg, 2);
$range = "'" . $sheetName . "'!" . $newRange . (count($data) + 1000);
}
$options = ['valueInputOption' => 'RAW'];
if ($clear) {
$sheet->spreadsheets_values->clear($this->sheetId, $range, new \Google_Service_Sheets_ClearValuesRequest);
}
$body = new \Google_Service_Sheets_ValueRange(['values' => $data, 'majorDimension' => $columns ? 'COLUMNS' : 'ROWS']);
$ok = $sheet->spreadsheets_values->append($this->sheetId, $range, $body, $options);
}
I saw someone on the internet mentioning getLastColumn() as a function, but it's not available in my version of sheets API apparently or it's just not in this package.
google/apiclient v2.5.0
google/apiclient-services v0.138
google/auth v1.9.0
getLastColumn is an appscript method. Something like that is not available with the php client library is only going to give you google sheets api methods,
The only way to find out whats on the sheet is to buffer it and scan though as you are already doing. Unfortunately with PHP there is really no easy way of doing it.
$response = $service->spreadsheets_values->batchGet($spreadsheetId);
I dont use PHP, but I am 100% sure, that in Google API its closest things on PHP and Python, just syntax of languages would be different
So for get the first free column through Google Sheet API (using Python):
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
DOCUMENT_ID = '1ma8DG3IQJ377900iaFUPu9qXoThuP22buLgEILVfO1M'
def get_service_sacc():
creds_json = 'param-param-1344-fae81984f8a8.json'
scopes = ['https://www.googleapis.com/auth/spreadsheets']
creds_service = ServiceAccountCredentials.from_json_keyfile_name(creds_json, scopes).authorize(httplib2.Http())
return build('sheets', 'v4', http=creds_service)
sheet_values = get_service_sacc().spreadsheets().values()
_range = "A1:A9"
# or use _range = "Name of List!A1:A9", if u want to take info not from first list of sheets.
write = sheet_values.append(spreadsheetId=DOCUMENT_ID, range=_range, valueInputOption="USER_ENTERED",body={}).execute()
deal_id = str(write['updates']['updatedRange']).split('!')
little info about how get creds.json, if you wanna make thru this method (its from Service Account (https://cloud.google.com/iam/docs/service-accounts), create it, go to you Cloud Developer Console, create a some project, create service account, append it to project, and also after creation, click on three dots at actions (in account line), click Manage keys -> Add key -> Create new key -> json and end it, than download that json, and put it together in one directory of you project where u start you language logic.)
info about, how append works (https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/append)
Using the code given from Packagist (https://packagist.org/packages/patreon/patreon?q=&p=6), I am unable to get the expected results. My code now logs the user in, and returns their data (which I can view via var_dump), but I'm having issues actually reading it.
According to the Patreon API documentation, the data received from the API is automatically set as an array, unless specified otherwise. I'm running the exact code from their website but their API is returning an object, and I'm not sure how to read the user's data and pledge information from it. I've tried setting the return data as an array or json without any luck. I'm just getting this jumbled mess when I convert the API response into an array.
Screenshot - https://i.gyazo.com/3d19f9422c971ce6e082486cd01b0b92.png
require_once __DIR__.'/vendor/autoload.php';
use Patreon\API;
use Patreon\OAuth;
$client_id = 'removed';
$client_secret = 'removed';
$redirect_uri = "https://s.com/redirect";
$href = 'https://www.patreon.com/oauth2/authorize?response_type=code&client_id=' . $client_id . '&redirect_uri=' . urlencode($redirect_uri);
$state = array();
$state['final_page'] = 'http://s.com/thanks.php?item=gold';
$state_parameters = '&state=' . urlencode( base64_encode( json_encode( $state ) ) );
$href .= $state_parameters;
$scope_parameters = '&scope=identity%20identity'.urlencode('[email]');
$href .= $scope_parameters;
echo 'Click here to login via Patreon';
if (isset($_GET['code']))
{
$oauth_client = new OAuth($client_id, $client_secret);
$tokens = $oauth_client->get_tokens($_GET['code'], $redirect_uri);
$access_token = $tokens['access_token'];
$refresh_token = $tokens['refresh_token'];
$api_client = new API($access_token);
$campaign_response = $api_client->fetch_campaign();
$patron = $api_client->fetch_user();
$patron = (array)$patron;
die(var_dump($patron));
}
I want to be able to view the user's data and pledge information. I've tried things such as $patron->data->first_name, $patron['data']['first_name'], etc. which have all thrown errors about the index of the array not being found.
You've probably already figured something out but I ran into the same thing and thought I'd share a solution here.
The JSONAPIResource object that the patreon library returns has a few specific methods that can return the individual pieces of data in a readable format.
import patreon
from pprint import pprint
access_token = <YOUR TOKEN HERE> # Replace with your creator access token
api_client = patreon.API(access_token)
campaign_response = api_client.fetch_campaign()
campaign = campaign_response.data()[0]
pprint(campaign.id()) # The campaign ID (or whatever object you are retrieving)
pprint(campaign.type()) # Campaign, in this case
pprint(campaign.attributes()) # This is most of the data you want
pprint(campaign.attribute('patron_count')) # get a specific attribute
pprint(campaign.relationships()) # related entities like 'creator' 'goals' and 'rewards'
pprint(campaign.relationship('goals'))
pprint(campaign.relationship_info())
# This last one one ends up returning another JSONAPIResource object with it's own method: .resource() that returns a list of more objects
# for example, to print the campaign's first goal you could use:
pprint( campaign.relationship_info('goals').resource()[0].attributes() )
Hope that helps someone!
I am trying to use mongodb full text search for showing jobs list. I have done all the necessary steps to create the text indexes and enable the full text search feature on the database and everything is working fine except from the full text search using PHP 5.6.
use the below code in php for full text:
<?php
$username = 'mongodbusername';
$password = 'changeMe';
$m = new MongoClient("mongodb://myadmin1:myadmin123#localhost/dbname");
//$m = new MongoClient("mongodb://localhost", array("username" => $username, "password" => $password,"db" => "jobma_integrations"));
$db = $m->integrations; // this is your dbname
$crawlingCollection = $db->crawled_jobs; // this is your collection name
$c = $crawlingCollection->find(
['$text' => ['$search' => "sales \"ardmore\""]], // this \"ardmore\" is used for exact match and sales will be match with any where
['score'=> ['$meta'=>'textScore']]
)->sort(
['score'=> ['$meta'=>'textScore']]
);
echo "<pre>";
var_dump(iterator_to_array($c));
?>
I am trying to integrate First Data e4 Gateway using PHP. I downloaded the VinceG/php-first-data-api PHP First Data Service API class. The code comes with some examples.
I have my Terminal ID (API_LOGIN) and Password (32 character string).
What confuses me is that when I use one of the examples, I don't know how to tell the class that I want to use the demo url, not the production url.
The class comes with two constants:
const LIVE_API_URL = 'https://api.globalgatewaye4.firstdata.com/transaction/';
const TEST_API_URL = 'https://api.demo.globalgatewaye4.firstdata.com/transaction/';
In the First Data console, when I generated my password, it said to use the v12 api, /transaction/v12, so I changed the protected $apiVersion = 'v12';
All I want to do is write my first development transaction using First Data e4. I have yet to get any kind of response. Obviously I need a lot of hand holding to get started.
When I set up a website to use BalancedPayments, they have a support forum that's pretty good, and I was able to get that running fairly quickly. First Data has a lot of documentation, but for some reason not much of it has good PHP examples.
My hope is that some expert has already mastered the VinceG/php-first-data-api, and can help me write one script that works.
Here's the pre-auth code I'm using, that invokes the FirstData class:
// Pre Auth Transaction Type
define("API_LOGIN", "B123456-01");
define("API_KEY", "xxxxxxxxxxyyyyyyyyyyyyzzzzzzzzzz");
$data = array();
$data['type'] = "00";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vance";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33333";
$data['cvv'] = "123";
$data['address'] = "1111 OCEAN BLVD MIAMI FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
// Charge
$firstData->setTransactionType(FirstData::TRAN_PREAUTH);
$firstData->setCreditCardType($data['type'])
->setCreditCardNumber($data['number'])
->setCreditCardName($data['name'])
->setCreditCardExpiration($data['exp'])
->setAmount($data['amount'])
->setReferenceNumber($orderId);
if($data['zip']) {
$firstData->setCreditCardZipCode($data['zip']);
}
if($data['cvv']) {
$firstData->setCreditCardVerification($data['cvv']);
}
if($data['address']) {
$firstData->setCreditCardAddress($data['address']);
}
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
My number one problem was that I had not created (applied for, with instant approval) a
demo account on First Data. I didn't realize this was a separate thing on First Data. On Balanced Payments, for instance, you have one account, and you can run your script on a test url with test values.
From the Administration panel, click "Terminals", then your Gateway number on the ECOMM row (will look something like AH1234-03), then you have to click "Generate" on password save it to your personal notes), then click UPDATE.
Now replace your parameter values in your test scripts. I use a variable assignment block that looks something like this:
define("API_LOGIN", "AH1234-05"); //fake
define("API_KEY", "44p7797xxx790098z1z2n6f270ys1z0x"); //fake
$data = array();
$data['type'] = "03";
$data['number'] = "4111111111111111";
$data['name'] = "Cyrus Vancce";
$data['exp'] = "0618";
$data['amount'] = "100.00";
$data['zip'] = "33320";
$data['cvv'] = "123";
$data['address'] = "1234 N OCEAN BLVD MIAMI BEACH FL";
$orderId = "0001";
require_once("FirstData.php");
$firstData = new FirstData(API_LOGIN, API_KEY, true);
at the end of the VinceG test scripts, I output my gateway response with a print_r, like this:
$firstData->process();
// Check
if($firstData->isError()) {
echo "!!!";
// there was an error
} else {
echo "###";
// transaction passed
}
echo "<pre>";
print_r($firstData);
This question already has answers here:
How do I get video durations with YouTube API version 3?
(7 answers)
Closed 4 years ago.
I want to get the duration of a Youtube video. Here's the code I tried:
$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
Please check the XML file. I got the title of this video. I want to get duration from <yt:duration seconds='29'/>.
How to get the seconds attribute this <yt> tag?
Due to the upcoming deprecation of the YouTube v2 API, here is an updated solution.
Start by cloning the Google API PHP Client here
Next, you'll want to register an application with Google here by creating a new Project, turning on the YouTube Data API under the "APIs and auth → API" section, and
Create a new OAuth Client ID under "APIs and auth → Credentials" and add the full path to your redirect URI list. (i.e. http://example.com/get_youtube_duration.php)
Use this code (which was adapted from this sample code), while making sure to fill in the $OAUTH2_CLIENT_ID and $OAUTH2_CLIENT_SECRET variables with your own values from step 3.
Hardcode a value for the $videoId variable or set it using the video_id get parameter (i.e. http://example.com/get_youtube_duration.php?video_id=XXXXXXX)
Visit your script, click the link to authorize the app and use your google account to get a token, which redirects you back to your code and will display the duration.
Here is your output:
Video Duration
0 mins
29 secs
Some additional resources:
https://developers.google.com/youtube/v3/docs/videos#contentDetails.duration
https://developers.google.com/youtube/v3/docs/videos/list
The following works for the V2 API only.
This worked for me based on the assumption that there is only one duration element in the feed.
<?php
$vidID="voNEBqRZmBc";
//http://www.youtube.com/watch?v=voNEBqRZmBc
$url = "http://gdata.youtube.com/feeds/api/videos/". $vidID;
$doc = new DOMDocument;
$doc->load($url);
$title = $doc->getElementsByTagName("title")->item(0)->nodeValue;
$duration = $doc->getElementsByTagName('duration')->item(0)->getAttribute('seconds');
print "TITLE: ".$title."<br />";
print "Duration: ".$duration ."<br />";
Output:
TITLE: Introducing iTime
Duration: 29
Here it is YouTube API V3, with example of getting video duration, but do not forget to create your API key at https://console.developers.google.com/project
$vidkey = "cHPMH2sa2Q" ; video key for example
$apikey = "xxxxxxxxxxxxxxxxxxxxx" ;
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
A short and simple solution using SimpleXML:
function getYouTubeVideoDuration($id) {
$xml = simplexml_load_file('http://gdata.youtube.com/feeds/api/videos/'.$id);
return strval($xml->xpath('//yt:duration[#seconds]')[0]->attributes()->seconds);
}
All the prev answers provide the duration in a text format:
This solution will give you the hours / minutes / seconds for you to transform to whatever format you would like:
function getDurationInSeconds($talkId){
$vidkey = $talkId;
$apikey = "xxxxx";
$dur = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$vidkey&key=$apikey");
$VidDuration =json_decode($dur, true);
foreach ($VidDuration['items'] as $vidTime)
{
$VidDuration= $vidTime['contentDetails']['duration'];
}
preg_match_all('/(\d+)/', $VidDuration, $parts);
$hours = intval(floor($parts[0][0]/60) * 60 * 60);
$minutes = intval($parts[0][0]%60 * 60);
$seconds = intval($parts[0][1]);
$totalSec = $hours + $minutes + $seconds; // This is the example in seconds
return $totalSec;
}
Very easy
function getYoutubeDuration($videoid) {
$xml = simplexml_load_file('https://gdata.youtube.com/feeds/api/videos/' . $videoid . '?v=2');
$result = $xml->xpath('//yt:duration[#seconds]');
$total_seconds = (int) $result[0]->attributes()->seconds;
return $total_seconds;
}
//now call this pretty function. As parameter I gave a video id to my function and bam!
echo getYoutubeDuration("y5nKxHn4yVA");
You can also get the duration in JSON
$video_id = "<VIDEO_ID>";
http://gdata.youtube.com/feeds/api/videos/$video_id?v=2&alt=jsonc
Oh! Sorry you can get it by:
$duration = $xml->getElementsByTagName('duration')->item(0)->getAttribute('seconds');