How to get Google Contacts information using Google OAuth? - php

I am new to OAuth, and want to create a page that gets the user's contact list from Google using the OAuth system so they don't have to login.
How do I do this? I am using php, so I would really appreciate if there is example code that does this. I can't seem to find it on Google.
Please help!
Thanks

For general OAuth principles to access Google, you might find Google's OAuth playground very useful (contacts are included there).
This is a very basic example (using the php oauth pecl extension and simplexml, it just prints out the names of the 25 first contacts):
<?php
$cons_key="your consumer key";
$cons_sec="your consumer secret";
$callback="http://".$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
$req_token_url="https://www.google.com/accounts/OAuthGetRequestToken";
$auth_token_url="https://www.google.com/accounts/OAuthAuthorizeToken";
$acc_token_url="https://www.google.com/accounts/OAuthGetAccessToken";
$scope="https://www.google.com/m8/feeds/";
$scopes=urlencode($scope);
$req_scope_token_url=$req_token_url."?scope=".$scopes;
$endpoint="https://www.google.com/m8/feeds/contacts/default/full/";
session_start();
if(!isset($_GET['oauth_token']) && $_SESSION['state']==1) $_SESSION['state'] = 0;
try {
$oauth = new OAuth($cons_key,$cons_sec);
if(!isset($_GET['oauth_token']) && !$_SESSION['state']) {
$oauth = new OAuth($cons_key,$cons_sec);
$oauth->setRequestEngine(OAUTH_REQENGINE_CURL);
$request_token_info = $oauth->getRequestToken($req_scope_token_url,$callback);
if(!empty($request_token_info)) {
$_SESSION['token']=$request_token_info['oauth_token'];
$_SESSION['secret']=$request_token_info['oauth_token_secret'];
$_SESSION['state']=1;
header('Location: '.$auth_token_url.'?oauth_token='.$_SESSION['token']);
exit;
}
} else if($_SESSION['state']==1) {
$oauth->setToken($_GET['oauth_token'],$_SESSION['secret']);
$access_token_info = $oauth->getAccessToken($acc_token_url);
$_SESSION['state'] = 2;
$_SESSION['token'] = $access_token_info['oauth_token'];
$_SESSION['secret'] = $access_token_info['oauth_token_secret'];
}
$oauth->fetch($endpoint);
parseAtom($oauth->getLastResponse());
} catch(OAuthException $E) {
print_r($E);
}
function parseAtom($atomstring) {
global $oauth;
$atom=simplexml_load_string($atomstring);
foreach ($atom->entry as $entry) {
print $entry->title.", ";
}
}
?>
You can see the above code in action here.
Installing (configuring) the oauth pecl extension can be tricky, you may have to check your php.ini and/or specify a requestengine.

Hope my post helpful to all (Google contact list reader in PHP(Google OAuth))
http://anandafit.info/2011/03/08/google-contact-list-reader-in-php-google-oauth/

You need to start with Google Contacts Data API and OAuth, when you're done, this should be enough for a reference.

OK. first of all futtta i had some problems with pecl and pear stuff. so i decided to stick with ZEND. I do appreciate you posting though, your code still helped me :-)....
here is what i've got so far, taking some of the code from the ibm page posted above, but altering it to use oauth to get in.
<?php
session_start();
require_once 'common.php';
require_once 'Zend/Oauth/Consumer.php';
require_once 'Zend/Crypt/Rsa/Key/Private.php';
require_once 'Zend/Gdata.php';
require_once 'Zend/Gdata/Query.php';
$oauthOptions = array(
'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
'version' => '1.0',
'consumerKey' => 'PUT KEY HERE',
'consumerSecret' => 'PUT KEY HERE',
'signatureMethod' => 'HMAC-SHA1',
'requestTokenUrl' => 'https://www.google.com/accounts/OAuthGetRequestToken',
'userAuthorizationUrl' => 'https://www.google.com/accounts/OAuthAuthorizeToken',
'accessTokenUrl' => 'https://www.google.com/accounts/OAuthGetAccessToken'
);
?>
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Listing contacts</title>
<style>
body {
font-family: Verdana;
}
div.name {
color: red;
text-decoration: none;
font-weight: bolder;
}
div.entry {
display: inline;
float: left;
width: 400px;
height: 150px;
border: 2px solid;
margin: 10px;
padding: 5px;
}
td {
vertical-align: top;
}
</style>
</head>
<body>
<?
$consumer = new Zend_Oauth_Consumer($oauthOptions);
if (!isset($_SESSION['ACCESS_TOKEN_GOOGLE'])) {
if (!empty($_GET)) {
$token = $consumer->getAccessToken($_GET, unserialize($_SESSION['REQUEST_TOKEN_GOOGLE']));
$_SESSION['ACCESS_TOKEN_GOOGLE'] = serialize($token);
} else {
$token = $consumer->getRequestToken(array('scope'=>'http://www.google.com/m8/feeds'));
$_SESSION['REQUEST_TOKEN_GOOGLE'] = serialize($token);
$consumer->redirect();
exit;
}
} else {
$token = unserialize($_SESSION['ACCESS_TOKEN_GOOGLE']);
//$_SESSION['ACCESS_TOKEN_GOOGLE'] = null;
}
$http = $token->getHttpClient($oauthOptions);
$gdata = new Zend_Gdata($http);
$gdata->setMajorProtocolVersion(3);
$gdata->getHttpClient()->setRequestScheme(Zend_Oauth::REQUEST_SCHEME_QUERYSTRING);
$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full?);
//$query->setMaxResults(10);
$feed = $gdata->getFeed($query);
?>
<h2><?php echo $feed->title; ?></h2>
<div>
<?php echo $feed->totalResults; ?> contact(s) found.
</div>
<?php
// parse feed and extract contact information
// into simpler objects
$results = array();
foreach($feed as $entry){
$xml = simplexml_load_string($entry->getXML());
$obj = new stdClass;
$obj->name = (string) $entry->title;
$obj->orgName = (string) $xml->organization->orgName;
$obj->orgTitle = (string) $xml->organization->orgTitle;
foreach ($xml->email as $e) {
$obj->emailAddress[] = (string) $e['address'];
}
foreach ($xml->phoneNumber as $p) {
$obj->phoneNumber[] = (string) $p;
}
foreach ($xml->website as $w) {
$obj->website[] = (string) $w['href'];
}
$results[] = $obj;
}
?>
<?php
// display results
foreach ($results as $r) {
?>
<div class="entry">
<div class="name"><?php echo (!empty($r->name)) ?
$r->name : 'Name not available'; ?></div>
<div class="data">
<table>
<tr>
<td>Organization</td>
<td><?php echo $r->orgName; ?></td>
</tr>
<tr>
<td>Email</td>
<td><?php echo #join(', ', $r->emailAddress); ?></td>
</tr>
<tr>
<td>Phone</td>
<td><?php echo #join(', ', $r->phoneNumber); ?></td>
</tr>
<tr>
<td>Web</td>
<td><?php echo #join(', ', $r->website); ?></td>
</tr>
</table>
</div>
</div>
<?php
}
?>
</body>
</html>
There are still some problems, for me it only posts 25 results and i cannot seem to get setmaxresults to work... there seems to be problems with ZEND for that... if someone knows a work around, please post.
b

Comment out the setRequestScheme method call and use max-results and you should be able to get more than 25 entries.
//$gdata->getHttpClient()->setRequestScheme(Zend_Oauth::REQUEST_SCHEME_QUERYSTRING);
$query = new Zend_Gdata_Query('http://www.google.com/m8/feeds/contacts/default/full/?max-results=999999');

Related

How can I found out if an infusionsoft contact has a specific tag id

Does anyone have an example of php code to check to see if an Infusionsoft contact has a specific tag? I am using the following code to insert into Infusionsoft Campaign Builder image feature. The code is a file called buspass.php. After I scanned the image with the applied code it does not display the "Display the Route #'s" as echoed with the "If" statements. After the scan the image looks like this: image after QR Scan
Here's what I have:
<html>
<code>
<p><img style="display: block; margin-left: auto; margin-right:auto;" src="https://d1yoaun8syyxxt.cloudfront.net/ib945-9ac2eb8c510b-4ac6-b282-bcd4552812f1-v2" alt="TOPA LOGO" width="80%" /></p>
<?php
require_once("isdk.php");
$app = new iSDK;
// Establish Connnection
if ($app->cfgCon("ib945"));
// Confirm Connection with Date Display
date_default_timezone_set("America/Phoenix");
echo "<div align='center'><h2>Scanned on " . $currentDate =
date("Y/m/d # h:i:sa") . "<br/></h2></div>";
echo "<div align='center'><img src='https://d1yoaun8syyxxt.cloudfront.net/ib945-321c85f8-dafe-45a1-9388-ef7fb6b7b4ec-v2'/></div>";
// Call Infusiosoft Contact Information
$Id = $_REQUEST['id'];
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$email = $_REQUEST['email'];
$phone1 = $_REQUEST['phone1'];
$sfname1 = $_REQUEST['sfname1'];
$slname1 = $_REQUEST['slname1'];
$sfname2 = $_REQUEST['sfname2'];
$slname2 = $_REQUEST['slname2'];
$sfname3 = $_REQUEST['sfname3'];
$slname3 = $_REQUEST['slname3'];
$sfname4 = $_REQUEST['sfname4'];
$slname4 = $_REQUEST['slname4'];
$sfname5 = $_REQUEST['sfname5'];
$slname5 = $_REQUEST['slname5'];
$sfname6 = $_REQUEST['sfname6'];
$slname6 = $_REQUEST['slname6'];
//Display Parent/Guardian Information
echo "<div align='center'><h1><u>PARENT/GUARDIAN INFORMATION:</u>
<br/><br/>
<div align='left'>Contact ID: $Id<br/>
Name: $fname $lname<br/>
Email: $email<br/>
Phone: $phone1<br/></h1></div>";
//Display Scholar Names
echo strtoupper ("<div align='center'><h1><u>BUS RIDER SCHOLAR
NAME(S):</u></h1></div>
<div align='left'><strong><font size='24'>$sfname1
$slname1<br/>$sfname2 $slname2<br/>$sfname3 $slname3<br/>$sfname4
$slname4<br/>$sfname5 $slname5<br/>$sfname6 $slname6</strong>
</div>");
//Display Route #'s
If($tagId == 1184 || $tagId == 1192) {
echo 'Route #1';
}
If($tagId == 1182 || $tagId == 1194) {
echo 'Route #2';
}
If($tagId == 1186 || $tagId == 1196) {
echo 'Route #3';
}
?>
<p><img style="display: block; margin-left: auto; margin-right:auto;" src="https://d1yoaun8syyxxt.cloudfront.net/ib945-585a8b93-7096-4240-b543-e40ffecc5699-v2" alt="Thumbs Up" width="60%" />
</code>
</html>
I am not sure what is in the QR Scan, but it looks like you are passing the information for the contact and other individuals in the URL, is that correct? It also looks like you are using the iSDK. If you have the iSDK files you should be able to use something like this:
If you need to get the contact information:
$app = new iSDK;
if (!$app->cfgCon("CONNNAME"))
exit;
$returnFields = array('Email', 'FirstName', 'LastName', 'Company');
$conDat = $app->dsLoad("Contact", $contact_id, $returnFields);
if (isset($conDat['Email'])){
$email = $conDat['Email'];
}
if (isset($conDat['FirstName'])){
$FirstName = $conDat['FirstName'];
}
if (isset($conDat['LastName'])){
$LastName = $conDat['LastName'];
}
if (isset($conDat['Company'])){
$Company = $conDat['Company'];
}
You can of course change the fields to what you need...
To get tags:
$app = new iSDK;
if (!$app->cfgCon("CONNNAME"))
exit;
$fields = array('Id', 'Groups');
$results = $app->loadCon($contact_id,$fields);
$BufferTEXT = "0,".$results['Groups'];
switch (true) {
case strpos($BufferTEXT,'1184') || strpos($BufferTEXT,'1192'):
echo 'Route #1';
break;
case strpos($BufferTEXT,'1182') || strpos($BufferTEXT,'1194'):
echo 'Route #1';
break;
case strpos($BufferTEXT,'1186') || strpos($BufferTEXT,'1196'):
echo 'Route #1';
break;
default:
echo 'No Assigned Route';
break;
}
The reason I use the $BufferTEXT, is because if your tag is the first one the strpos function won't catch it. So adding a 0, to the beginning of the array fixed it for me.
I did not test the code, I have used similar code in the past and it worked for me. I hope this points you in the right direction.
I actually test this code and it works, assuming you are actually connecting using your connection string, not just putting your application Id in the cfgCon and also that all the names and contactId is coming into the URL for the QR Code:
<html>
<code>
<p><img style="display: block; margin-left: auto; margin-right:auto;" src="https://d1yoaun8syyxxt.cloudfront.net/ib945-9ac2eb8c510b-4ac6-b282-bcd4552812f1-v2" alt="TOPA LOGO" width="80%" /></p>
<?php
include 'isdk.php';
$apiKey = 'YOURAPIKEY';
$secret = 'YOURSECRETKEY';
$app = new iSDK;
//I am assuming you have set up the connection string???
if (!$app->cfgCon("ib945"))
exit;
// Confirm Connection with Date Display
date_default_timezone_set("America/Phoenix");
echo "<div align='center'><h2>Scanned on " . $currentDate =
date("Y/m/d # h:i:sa") . "<br/></h2></div>";
echo "<div align='center'><img src='https://d1yoaun8syyxxt.cloudfront.net/ib945-321c85f8-dafe-45a1-9388-ef7fb6b7b4ec-v2'/></div>";
// Call Infusionsoft Contact Information
// I am assuming that you are passing this data in the url???
$Id = $_REQUEST['id'];
$fname = $_REQUEST['fname'];
$lname = $_REQUEST['lname'];
$email = $_REQUEST['email'];
$phone1 = $_REQUEST['phone1'];
$sfname1 = $_REQUEST['sfname1'];
$slname1 = $_REQUEST['slname1'];
$sfname2 = $_REQUEST['sfname2'];
$slname2 = $_REQUEST['slname2'];
$sfname3 = $_REQUEST['sfname3'];
$slname3 = $_REQUEST['slname3'];
$sfname4 = $_REQUEST['sfname4'];
$slname4 = $_REQUEST['slname4'];
$sfname5 = $_REQUEST['sfname5'];
$slname5 = $_REQUEST['slname5'];
$sfname6 = $_REQUEST['sfname6'];
$slname6 = $_REQUEST['slname6'];
//Display Parent/Guardian Information
echo "<div align='center'><h1><u>PARENT/GUARDIAN INFORMATION:</u>
<br/><br/>
<div align='left'>Contact ID: $Id<br/>
Name: $fname $lname<br/>
Email: $email<br/>
Phone: $phone1<br/></h1></div>";
//Display Scholar Names
echo strtoupper ("<div align='center'><h1><u>BUS RIDER SCHOLAR
NAME(S):</u></h1></div>
<div align='left'><strong><font size='24'>$sfname1
$slname1<br/>$sfname2 $slname2<br/>$sfname3 $slname3<br/>$sfname4
$slname4<br/>$sfname5 $slname5<br/>$sfname6 $slname6</strong>
</div>");
//Display Route #'s
$fields = array('Id', 'Groups');
$results = $app->loadCon($Id,$fields);
$BufferTEXT = "0,".$results['Groups'];
switch (true) {
case strpos($BufferTEXT,'1184') || strpos($BufferTEXT,'1192'):
echo 'Route #1';
break;
case strpos($BufferTEXT,'1182') || strpos($BufferTEXT,'1194'):
echo 'Route #2';
break;
case strpos($BufferTEXT,'1186') || strpos($BufferTEXT,'1196'):
echo 'Route #3';
break;
default:
echo 'No Assigned Route';
break;
}
?>
<p><img style="display: block; margin-left: auto; margin-right:auto;" src="https://d1yoaun8syyxxt.cloudfront.net/ib945-585a8b93-7096-4240-b543-e40ffecc5699-v2" alt="Thumbs Up" width="60%" />
</code>
</html>

Cannot add php code to a variable?

I am trying to create a PHP file each time a user registers my website. I use the following code to create the file in my register.php :
The thing is, my create file function works but the variable $data doesn't give any result. When I run that $data as a single variable in a different PHP file it still doesn't work.
What did I do wrong about setting the variable.
// STARTING to create a file
$my_file = "$username.php";
$handle = fopen("give/$my_file", 'w') or die('Cannot open file: '.$my_file);
//----------- BEGINNING OF THE PHP DATA TO WRITE TO NEW FILE ----------
$data = "<?
require('../config.inc.php');
$damned_user = $username;
if ( $_COOKIE['damn_given'] != TRUE ) {
$sql = mysql_query(\"SELECT * FROM users WHERE username='$damned_user' LIMIT 1\");
if(mysql_num_rows($sql) == 1){
$row = mysql_fetch_array($sql);
// $row['field'];
$damned_user_id = $row['id'];
if($_SESSION['id'] == $damned_user_id) {
} else {
$taken = $row['taken_damns'];
$taken_damns = $taken + 1;
$taking_sql = \"UPDATE users SET taken_damns='$taken_damns' WHERE username='$damned_user' \";
if (mysql_query($taking_sql)) {
setcookie(\"damn_given\", TRUE, time()+3600*24);
$date = date(\"Y-m-d H:i:s\");
$ip = $_SERVER['REMOTE_ADDR'];
$damns_table = \"INSERT INTO damns (id, from_ip, user_damned, when_damned) VALUES ('','$ip','$damned_user','$date') \";
if ( mysql_query($damns_table)) {
} else {
echo \"Couldn't save damn to damns table in database!\";
}
if ( $_SESSION['logged'] == TRUE ) {
$session_id = $_SESSION['id'];
$giving_sql = \"UPDATE users SET given_damns='$taken_damns' WHERE id='$session_id'\";
if ( mysql_query($giving_sql ) ) {
} else {
echo ('Error giving damn!');
}
}
}
else
{
die (\"Error taking damn!\");
}
}
} else {
die(\"Error first sql!\");
}
}
?>
<html>
<head>
<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />
<link rel=\"stylesheet\" href=\"/_common.css\" />
<link rel=\"stylesheet\" href=\"/_col_white.css\" />
<link rel=\"shortcut icon\" href=\"/favicon.ico\" /> <title>DamnIt.tk - Damned!</title>
</head>
<body>
<div id=\"main\">
<div class=\"center\"><img src=\"/_bnr_white.png\" style=\"width: 500px; height: 100px;\" alt=\"DamnIt Banner\" /></div>
<table class=\"tmid\" style=\"width: 100%;\"><tr>
<td class=\"center\" style=\"width: 25%;\">Profile</td>
<td class=\"center\" style=\"width: 25%;\">Options</td>
<td class=\"center\" style=\"width: 25%;\">Stats</td>
<td class=\"center\" style=\"width: 25%;\">Log out</td>
</tr></table> <h1>Give a Damn</h1>
<?
if ( isset($_COOKIE['damn_given'])) {
?>
<h2>You have already given a Damn to <? echo $damned_user ?> today!</h2><h3>Couldn't damn - try again tomorrow.</h3>
<?
}
elseif ( $_SESSION['id'] == $damned_user_id ) {
?>
<h2>You cannot damn yourself!</h2>
<?
} else{ ?> <h2>Damn given!</h2><h3>You have given a Damn to <? echo $damned_user ?>.</h3> <? } ?>
</div></body>
</html>";
//------- END OF PHP WHICH MUST BE WRITTEN TO NEW FILE ---------
fwrite($handle, $data);
fclose($handle);
// finished with the file
Try NOWDOC:
$data = <<<'END'
Your PHP code here
END;
This will allow for any string, without need for escaping.
However, please consider what you're doing very carefully!
Also... you wouldn't happen to be trying to rip off this site of mine, would you? http://giveadamn.co.uk/
(source: giveadamn.co.uk)
Because if so, you're doing it wrong. .htaccess, mate ;)
RewriteEngine on
RewriteRule give/(.*) give.php?user=$1 [L]

get the latest excel file and convert into html using php excel reader

Can you help me with this? i don't know what to put or what to start to solve this.
i have an excel reader which is working fine, converting my excel into html and i have a code that detect the latest file in the directory
my problem is, what code should i put to display or get the latest excel file in the directory using php excel reader
here's the code that i have. Please help me
<?php
class ReportViewer
{
public $extension = array ( 'xlsx', 'xls', 'html', 'htm', 'csv' );
public function getLatestReport($report)
{
$reports_directory = preg_split("/[\-]/", $report);
//$latest_files = array();
if (!ctype_alpha($report))
$directory = $reports_directory[0].'/'.$reports_directory[1];
else
$directory = $reports_directory[0];
$dir_contents = new RecursiveDirectoryIterator($directory);
foreach (new RecursiveIteratorIterator($dir_contents) as $filename => $file)
{
if (preg_match("/\.(" . implode("|", $this->extension) . ")*$/i", $file->getFileName()/*, $filename*/))
{
$latest_files[$file->getMTime()] = array($directory, $file->getFileName(), $file->getPath());
//echo $file->getFileName() . "\n";
}
}
krsort($latest_files);
//print_r($latest_files);
// print_r($timeMod);
return $latest_files;
}
}
?>
<html>
<head>
<style type="text/css">
table {
border-collapse: collapse;
}
td {
border: 1px solid black;
padding: 0 0.5em;
}
</style>
</head>
<body>
<?php
include 'reader.php';
$excel = new Spreadsheet_Excel_Reader();
$lastest = new ReportViewer();
?>
Sheet 1:<br/><br/>
<table>
<?php
$excel->read('battery-report.xls');
$x=1;
while($x<=$excel->sheets[0]['numRows']) {
echo "\t<tr>\n";
$y=1;
while($y<=$excel->sheets[0]['numCols']) {
$cell = isset($excel->sheets[0]['cells'][$x][$y]) ? $excel->sheets[0]['cells'][$x][$y] : '';
echo "\t\t<td>$cell</td>\n";
$y++;
}
echo "\t</tr>\n";
$x++;
}
?>
</table><br/>
</body>
</html>
you are returning an array from getLatestReport() so use the first file in the list for your excel reader. if you can return the only required filename form getLatestReport() you can simply use $excel->read($lastest->getLatestReport('battery-report.xls'));
try this
<table>
<?php
$latestFiles=$lastest->getLatestReport('battery-report.xls');
$excel->read($latestFiles[0]);
$x=1;

Magento get function trough php

I am trying to get some data from Magento trough php, it works but I need to add multiple collections and now I am stuck. I am just a beginner so please forgive me :-)
I am using below code to get customer details, this works ok.
Now I need to add the customer/address to get the address details to fill the last column with the zipcode, anybody know how to do that?
<?php
function getcustomers() {
/* Magento's Mage.php path
* Mage Enabler users may skip these lines
*/
require_once ("app/Mage.php");
umask(0);
Mage::app("nl");
/* Magento's Mage.php path */
/* Get customer model, run a query */
$collection = Mage::getModel('customer/customer')
//$collection = Mage::getModel('customer/address')
->getCollection()
->addAttributeToSelect('*');
$result = array();
foreach ($collection as $customer) {
$result[] = $customer->toArray();
}
return $result;
}
?>
<html>
<head>
<title>Customers</title>
<style>
table {
border-collapse: collapse;
}
td {
padding: 5px;
border: 1px solid #000000;
}
</style>
</head>
<body>
<table>
<tr>
<td>ID</td>
<td>Lastname</td>
<td>Firstname</td>
<td>Email</td>
<td>Is Active?</td>
<td>Date Created</td>
<td>Date Updated</td>
<td>Website ID</td>
<td>Store ID</td>
<td>Zip Code</td>
</tr>
<?php
$result = getcustomers();
if(count($result) > 0){
foreach($result as $key => $value){
echo "<tr>";
echo "<td>".$value['entity_id']."</td>";
echo "<td>".$value['lastname']."</td>";
echo "<td>".$value['firstname']."</td>";
echo "<td>".$value['email']."</td>";
echo "<td>";
echo $value['is_active'] == 1 ? "Yes" : "No";
echo "</td>";
echo "<td>".$value['created_at']."</td>";
echo "<td>".$value['updated_at']."</td>";
echo "<td>".$value['website_id']."</td>";
echo "<td>".$value['store_id']."</td>";
echo "<td>".$value['zipcode']."</td>";
echo "</tr>";
}
}else{
echo "<tr><td colspan=\"7\">No records found</td></tr>";
}
?>
</table>
</body>
</html>
Just want to say that I'm currently learning Magento, so my answer will not be totally working! I hope it'll help to push you in the right direction.
Just a note, you can just use $customer->getData() to return an array.
Then you can use $customer->getId() to get the id. Which you can then pass into the Address model
foreach($collection as $customer){
// You have an instance of the Customer already, so we can just use a magic get method
$cid = $customer->getId();
// Let's load this customers address, using a chain. Load the model (instantiate the class), then call load with the customer id
// You might want to check the alias on 'customer' to ensure it has address. You can find this in /app/code/core/Mage/Customer/etc/config.xml ln.251
$address = Mage::getModel('customer/address')->load($cid);
// Maybe we should look in here just in case - for debugging
var_dump($address); // or echo get_class($address);
// Here I would try one of the magic setter methods, which map to set<Thing> so you can play with this to see if it'll work
$address->setZipCode('12345');
// Then we should be able to save it, I think, this bit I'm not sure on.
$address->save();
}
As I say, this is just what I've learnt from the Magento U videos over the last week, hope it works!

PHP mailing database search

I made a PHP page that looks up Constant Contact e-mail addresses in a database and returns a table listing their name, e-mail address, and mailing list they are in. You enter the addresses here: Contact Lookup Tool along with your Constant Contact user name and password.
For some reason, only the last row of the results page has a list of mailing lists. The other ones have the word "Array," which I stripped out, so now those rows are blank. Here is a screen shot of what I mean:
http://www.advantage-computer.com/images/ScreenCap.png
They're all in a list, though. Here's the code for search.php. The form submits to that file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>List of Contacts</title>
<style type="text/css">
.hdr
{
margin-bottom: 0px;
padding-bottom: 0px;
}
</style>
</head>
<body>
<table width="75%">
<tr>
<td class="hdr">Name</td>
<td class="hdr">E-mail address</td>
<td class="hdr">List(s)</td>
</tr>
<tr>
<td colspan="3">
<hr style="padding:0; margin:0">
</td>
</tr>
<?PHP
require_once('./class.cc.php');
/*VARIABLES*/
$cc = new cc($_POST['userName'], $_POST['password']);
if($cc)
{
$strEmails = $_REQUEST['emails'];
$aryEmails = explode("\n", $strEmails);
$page = (isset($_GET['page'])) ? $_GET['page'] : 'lists';
$lists = $cc->get_lists($page);
/*METHODS*/
foreach ($aryEmails as $email)
{
if($lists)
{
foreach($lists as $k => $v)
{
$list = $v['Name'];
$page = (isset($_GET['page'])) ? $_GET['page'] : 'members';
$members = $cc->get_list_members($v['id'], $page);
if($members)
{
foreach($members as $k => $v)
{
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
}
}
}
}
}
$strLists = str_replace("Array", "", $strLists);
$strLists = substr($strLists, 0, -2);
$contact = $cc->query_contacts(trim($email));
if($contact)
{
$strName = $contact['Name'];
if(is_array($strName))
{
$strName = "";
}
echo
(
"<tr><td>".$strName."</td>".
"<td>".$contact['EmailAddress']."</td>".
"<td>".$strLists."</td></tr>"
);
}
else
{
echo("<tr><td colspan='3'>Could not find {$email}.</td></tr>");
}
}
}
else
{
echo "Invalid user name or password";
}
?>
</table>
</body>
</html>
Here is the class.cc file: http://advantage-computer.com/tools/class.cc.txt
Firstly, you should break out of that loop once you have matched a record, and you are not using $k so we can remove that from the loop too, eg:
if($members)
foreach($members as $v)
if($v['EmailAddress'] == $email)
{
$strLists .= $list . ", ";
break;
}
I would also add a line in there to debug whats in the $list variable when it is an array:
if (is_array($list))
var_dump($list);
I would say that whatever is setting "$_list['content']['ContactList']['Name']" in your class is not doing it correctly.
Thanks everyone for the replies. My brother found the problem. He changed
foreach ($aryEmails as $email){
...
}
to
foreach ($aryEmails as $tmpEmail){
$email = rtrim($tmpEmail);
...
}
It appears that it only matched the last line in the text area because there were still carriage returns in the e-mail array left over from the text area. He added rtrim to remove them.

Categories