PHP Google API Client v3 get contacts - php

I still have trouble with the new google_api_client php library. I'm trying to retrieve the user's contacts.
I'm very close to the right solution ... I mean, I just got all the results but a can't parse it.
Probably it's because I'm not strong with XML parser. After tests and tests ... I get this solution (based on the example file by Google):
...
$req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full");
$val = $client->getIo()->authenticatedRequest($req);
$response = simplexml_load_string($val->getResponseBody());
foreach($response->entry as $entry)
{
$child = $entry->children("http://schemas.google.com/g/2005");
$mail_info = $child->attributes();
}
...
In the $response I can get the title field where my contact's full name is stored, and in the $mail_info a got an object where i see the address field when I get the email address.
It's SAD and UGLY solution ... what if I want the company name, address ... phone numbers ... photos. Where are all these informations.
How can I use the Google response in a great and clean solution?
Anyone can give me some help.
Bye

What helped me was requesting JSON instead of XML. Try adding ?alt=json to the end of the URL in the request you make to google.
$req = new apiHttpRequest("https://www.google.com/m8/feeds/contacts/default/full?alt=json");
$val = $client->getIo()->authenticatedRequest($req);
$string = $val->getResponseBody();
$phparray = json_decode($string);
Certainly not child's play to get what you want but working with php arrays is probably easier.
For completeness this is the google contacts php example that we both probably found that helped us:
https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/contacts/simple.php
EDIT:
Here is another link that might help. In the comments it describes a cleaner of accessing contact's data using JSON.
http://25labs.com/import-gmail-or-google-contacts-using-google-contacts-data-api-3-0-and-oauth-2-0-in-php/
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl_file_get_contents($url);
$temp = json_decode($xmlresponse,true);
foreach($temp['feed']['entry'] as $cnt) {
echo $cnt['title']['$t'] . " --- " . $cnt['gd$email']['0']['address'] . "</br>";
}
and
$url = 'https://www.google.com/m8/feeds/contacts/default/full?max-results='.$max_results.'&alt=json&v=3.0&oauth_token='.$accesstoken;
$xmlresponse = curl_file_get_contents($url);
$temp = json_decode($xmlresponse,true);
foreach($temp['feed']['entry'] as $cnt) {
echo $cnt['title']['$t'] . " --- " . $cnt['gd$email']['0']['address'];
if(isset($cnt['gd$phoneNumber'])) echo " --- " . $cnt['gd$phoneNumber'][0]['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$street'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$street']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$neighborhood'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$neighborhood']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$pobox'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$pobox']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$postcode'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$postcode']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$city'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$city']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$region'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$region']['$t'];
if(isset($cnt['gd$structuredPostalAddress'][0]['gd$country'])) echo " --- " . $cnt['gd$structuredPostalAddress'][0]['gd$country']['$t'];
echo "</br>";
}

Related

firestore display values of data in php

how to display each record's values?
$collectionReference = $this->fsdb->collection('orders');
$documentReference = $collectionReference->document('MSKpcuedwxNmdLn2Ydsp');
$snapshot = $documentReference->snapshot();
echo "Hello " . $snapshot['userId'];
I am receiving this error:
ErrorException
Object of class Google\Cloud\Firestore\DocumentReference could not be converted to string
print_r() function works correctly but how to access each individual record?
I have been searching for hours to get this solved but I found no reference on web
Please help me in here...
A snapshot contains both data and metadata about the document. To get the data you need to call its data() method:
$collectionReference = $this->fsdb->collection('orders');
$documentReference = $collectionReference->document('MSKpcuedwxNmdLn2Ydsp');
$snapshot = $documentReference->snapshot();
if ($snapshot->exists()) {
printf('Document data:' . PHP_EOL);
echo "Hello " . $snapshot->data()['userId'];
} else {
printf('Document %s does not exist!' . PHP_EOL, $snapshot->id());
}
Also see the Firebase documentation on getting a document from Firestore.

How do you display the stream name? [ICECAST]

I took a part of PHP code from a different Stackoverflow question, and it works perfectly.
<?php header>
//Display IceCast Server Stats
$server = "***********"; //IP (x.x.x.x or domain name)
$iceport = "8070"; //Port
$iceurl = "live"; //Mountpoint
$online = "<font color=green><b>ONLINE</b> </font><br />";
$offline = "<font color=red><b>OFFLINE</b></font><br />";
if($fp = #fsockopen($server, $iceport, $errno, $errstr, '1')) {
fclose($fp);
$ice_status=$online;
echo "<p><b>DJ:</b> $ice_status";
$stats = file("http://" . $server . ":" . $iceport . "/status2.xsl");
$status = explode(",", $stats[5]);
$artist = explode("-", $status[5]);
echo " " . $artist[1];
echo " - ";
echo " " . $artist[2];
echo "<br />";
// echo "<b>Listeners:</b> <b> " . $status[3] . "</b>";
echo "</p>";
//echo "<br />";
//echo "<p><a href=http://" . $server . ":" . $iceport . "/" . $iceurl . " target=new><b>Listen!</b></a></p>";
} else {
$ice_status=$offline;
echo "<p><b>DJ:</b> $ice_status";
}
?>
<hr />
</center>
I'm trying to add the stream name, which is currently:
echo "DJ: $ice_status";
This displays DJ: ONLINE, but I want it to say DJ: (DJ Name/Stream Name)
I do believe its variables from status2.xsl, but I'm a complete noob at this, and can't seem to figure out how to use it. Could anyone tell me what streamname variable would be?
I was also wondering, is it possible to make it so the "nowplaying.php" refreshes, but my whole web page doesn't? I've tried an iframe, but it makes it look really bad, and has errors.
What my website looks like at the moment: https://i.stack.imgur.com/luc4O.jpg
I'd suggest having a look at TheFineManualâ„¢:
http://icecast.org/docs/icecast-2.4.1/server-stats.html#xslt
Especially the part about status-json.xsl. Make sure you are running an up to date version of Icecast. Icecast is available from all major Linux distributions in up to date packaging. Xiph provides independent packaging, which is useful if there are no up to date packages for a distribution, e.g. shortly after an Icecast release.
status2.xsl was an example file, and a bad one at that. It was removed from newer Icecast versions.

cache googlemaps geocoding results but my code is broken

I posted this question last night but I worded it wrong and didn't explain correctly. I am trying to cache googlemaps geocoding results for use in a firefighting mapping thing I have made and I am getting close to google's limits hence the need to cache the results. Help!
The code below kinda works however it creates a new sql record each time the code runs regardless of whether the address is already in the database. It seems to only call google once then saves the data, it then loads the data from the database ok and it looks like the rest works but I just can't see where I am going wrong.. As I said it creates a new record each and everytime the code runs and I would end up with a database full of the same identical records. My brain hurts but I really need to get this working so I can continue to help fire trucks to fires. :)
Oh, I am using the geocoding results on googlemaps (as permitted by the T&C) and this code is really only to get it working. I hope that makes sense and I hope someone can help... Thanks :)
<?php
$jobadd = "1000 BURWOOD HWY, BURWOOD";
// connect to the database
include('connect-db.php');
// get results from database and find needle
$result = mysql_query("SELECT * FROM geocache")
or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
$needle = '' . $row['address'] . '';
if (strpos($jobadd,$needle) !== false)
{
$status = "CACHED";
$latitude = '' . $row['latitude'] . '';
$longitude = '' . $row['longitude'] . '';
}
else
{
$status = "GOOGLE";
$address2 = "$jobadd, Victoria, Australia";
define("MAPS_HOST", "maps.google.com");
$base_url = "http://" . MAPS_HOST . "/maps/api/geocode/xml";
$request_url = $base_url . "?address=" . urlencode($address2) ."&sensor=false";
$xml = new SimpleXMLElement(file_get_contents($request_url));
$latitude = $xml->result->geometry->location->lat;
$longitude = $xml->result->geometry->location->lng;
// save the data to the database
mysql_query("INSERT geocache SET address='$jobadd', latitude='$latitude', longitude='$longitude' ")
or die(mysql_error());
}
}
echo $status;
echo '<BR>';
echo $jobadd;
echo '<BR>';
echo 'LAT:';
echo $latitude;
echo '<BR>';
echo 'LON:';
echo $longitude;
?>
Have you tried to output the result of strpos? The logic does not look incorrect. The issue is in the if condition. What do the records look like in the DB?

Getting video upload date with Zend Gdata Youtube API

I'm trying to get a list of videos for a specific user with all the details for the video (title, desc., date, tags...)
I can get pretty much everything I need, but can't figure out how to get the upload date.
I tried using getVideoRecorded() and getRecorded(), but both return nothing.
I can't seem to find anything related to this on Google, all I can find is class references which tell me that I have to use getVideoRecorded or getRecorded, but nothing more.
Am I doing something wrong? how can I get the upload date?
Current code:
$authenticationURL= 'https://www.google.com/accounts/ClientLogin';
$httpClient =
Zend_Gdata_ClientLogin::getHttpClient(
$username = $yt_username,
$password = $yt_password,
$service = 'youtube',
$client = null,
$source = '', // a short string identifying your application
$loginToken = null,
$loginCaptcha = null,
$authenticationURL);
$yt = new Zend_Gdata_YouTube($httpClient);
$feed = $yt->getUserUploads($yt_username);
foreach($feed as $item)
{
echo "<div>";
echo "<h4>title: " . $item->getVideoTitle() . "</h4>";
echo "<p>id: " . $item->getVideoId() . " | ";
echo "upload date: " . $item->getVideoRecorded() . "</p>";
echo "<p>description: " . $item->getVideoDescription() . "</p>";
echo "<p>tags: " . implode(", ", $item->getVideoTags()) . "</p>";
echo "</div>";
echo "<hr>";
}
You can try and extract the < published > or < updated > tags from the following xml:
http://gdata.youtube.com/feeds/api/videos/{$videoId}

How do I update an html table after each XML call to the server without refreshing the page?

I have a mySQL table loaded with 50 rows. Each row has the necessary information to process a credit card. When the user clicks on Process Credit Cards, query the table and display each row on the page using html. Once the data has been displayed on the page a scrip would begin to process each row through the merchant account and turn the corresponding row either red for decline or green for approve without refreshing the page after each transaction. I think I need to use AJAX or jQuery to make this happen but I'm not sure I'm headed in the right direction. Here is the script to process the transactions:
<?php
$request = new GatewayRequest();
$response = new GatewayResponse();
$service = new GatewayService();
$request->Set(GatewayRequest::MERCHANT_ID(), "111111111111111");
$request->Set(GatewayRequest::MERCHANT_PASSWORD(), "xxxxxxxxxxxx");
$time = time();
$request->Set(GatewayRequest::MERCHANT_CUSTOMER_ID(), $time . '.PHPTest');
$request->Set(GatewayRequest::MERCHANT_INVOICE_ID(), $time . '.SaleTest');
$request->Set(GatewayRequest::AMOUNT(), "9.99");
$request->Set(GatewayRequest::CARDNO(), "4111111111111111");
$request->Set(GatewayRequest::EXPIRE_MONTH(), "02");
$request->Set(GatewayRequest::EXPIRE_YEAR(), "2010");
$request->Set(GatewayRequest::CVV2(), "999");
$request->Set(GatewayRequest::CUSTOMER_FIRSTNAME(), "Joe");
$request->Set(GatewayRequest::CUSTOMER_LASTNAME(), "PHPTester");
$request->Set(GatewayRequest::EMAIL(), "phptest#fakedomain.com");
$request->Set(GatewayRequest::IPADDRESS(), $_SERVER['REMOTE_ADDR']);
$request->Set(GatewayRequest::BILLING_ADDRESS(), "123 Main St");
$request->Set(GatewayRequest::BILLING_CITY(), "Las Vegas");
$request->Set(GatewayRequest::BILLING_STATE(), "NV");
$request->Set(GatewayRequest::BILLING_ZIPCODE(), "89141");
$request->Set(GatewayRequest::BILLING_COUNTRY(), "US");
$request->Set(GatewayRequest::SCRUB(), "IGNORE");
$request->Set(GatewayRequest::CVV2_CHECK(), "IGNORE");
$request->Set(GatewayRequest::AVS_CHECK(), "IGNORE");
$service->SetTestMode(TRUE);
if ($service->PerformPurchase($request, $response)) {
print "Purchase succeeded\n";
print "Response Code: " .
$response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
print "Reasone Code: " .
$response->Get(GatewayResponse::REASON_CODE()) . "\n";
print "Auth No: " . $response->Get(GatewayResponse::AUTH_NO()) . "\n";
print "AVS: " . $response->Get(GatewayResponse::AVS_RESPONSE()) . "\n";
print "CVV2: " . $response->Get(GatewayResponse::CVV2_CODE()) . "\n";
print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
print "Account: " .
$response->Get(GatewayResponse::MERCHANT_ACCOUNT()) . "\n";
print "Scrub: " .
$response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
} else {
print "Purchase failed\n";
print "GUID: " . $response->Get(GatewayResponse::TRANSACT_ID()) . "\n";
print "Response Code: " .
$response->Get(GatewayResponse::RESPONSE_CODE()) . "\n";
print "Reasone Code: " .
$response->Get(GatewayResponse::REASON_CODE()) . "\n";
print "Exception: " .
$response->Get(GatewayResponse::EXCEPTION()) . "\n";
print "Scrub: " .
$response->Get(GatewayResponse::SCRUB_RESULTS()) . "\n";
}
?>
Will this type of code work with AJAX or jQuery without being rewritten? Any help would be appreciated.
Anything can be made to work without being rewritten, but you've set yourself up for a lot of headaches there. You'll probably have much better luck (and save yourself tons of time) by formatting all those print statements into an array and JSON encoding it. Obviously javascript loves JSON.

Categories