Link to home
Start Free TrialLog in
Avatar of phillystyle123
phillystyle123Flag for United States of America

asked on

need to generate a csv or spreadsheet when my form is submitted

hello

i need to generate a csv or spreadsheet  when my form is submitted. the file needs to be sent as an email attachment to a specified email address. i'm hoping there's a way to make it so the file has custom column headings  (but if it can't i can try to work around that).

i need this so my client can import contacts into constant contact - i don't want to use the custom contact email sign up form.

thanks for any direction!
Avatar of v2Media
v2Media
Flag of Australia image

You need to start with an exported contact file from constant contact. This way it's known how to format the csv file. Do an export and post the file.
sample code for csv
<?php
$export='';
include 'databaseconnection.php';
$Selectedvalue =$_POST["BackupCombo"];
$filename =$_POST["filename"];
$from = (!empty($_POST["from"])) ? $_POST["from"] : false;
$to = (!empty($_POST["from"])) ? $_POST["from"] : false;
 
//$to=$_POST["to"];
 
printf($filename);
//$datFrom =$from;
 
 
   // Convert to SQL format
   //$parts = explode("/", $datFrom);
   //$sqlDateFrom = $parts[2]."-".$parts[1]."-".$parts[0]; // 2009-08
//printf($sqlDateFrom);
//$datTo =$to;
//$parts = explode("/", $datTo);
  // $sqlDateTo = $parts[2]."-".$parts[1]."-".$parts[0];
//printf($datTO);		 
 
if($Selectedvalue=="User"&&$from ==''&&$to =='')
{
$export.="<html>
<table border=1>
<tr bgcolor='#000000'>
	<th><font color=white>UserName</font></th>
	<th><font color=white>NRIC</font></th>
	<th><font color=white>Race</font></th>
	<th><font color=white>Faxnumber</font></th>
	<th><font color=white>MaritalStatus</font></th>
	<th><font color=white>ContactNumberHp</font></th>
	<th><font color=white>Mobile</font></th>
	<th><font color=white>Email</font></th>
	<th><font color=white>OfficeTelNo</font></th>
	<th><font color=white>Website</font></th>
	<th><font color=white>Company</font></th>
	<th><font color=white>Agency</font></th>
	<th><font color=white>Address</font></th>
	<th><font color=white>UserId</font></th>
	<th><font color=white>Nationality</font></th>
	<th><font color=white>ContactNoRes</font></th>
</tr>"; 
$query=" Select * from useragentdetails";
 
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
	while($row=mysql_fetch_array($result)){ 
$export.="<tr><td>".$row['UserName']."</td><td>".$row['NRIC']."</td><td>".$row['Race']."</td><td>".$row['Faxnumber']."</td><td>".$row['Maritalstatus']."</td><td>".$row['ContactNumberhp']."</td><td>".$row['Mobile']."</td><td>".$row['Email']."</td><td>".$row['OfficeTelNo']."</td><td>".$row['Website']."</td><td>".$row['Company']."</td><td>".$row['Agency']."</td><td>".$row['Address']."</td><td>".$row['Userid']."</td><td>".$row['Nationality']."</td><td>".$row['Contactnores']."</td></tr>";
 
 
	}
}
 
 
$export.="</table>";
header("Content-type: application/ms-excel");
//header("Content-type: application/octet-stream");
header("Content-Disposition: inline; filename='$filename'");
header("Content-Description: PHP5 Generated Data" );
header("Content-Length: ".strlen($export));
print $export;
}

Open in new window

Avatar of phillystyle123

ASKER

thanks for the code stmani2005 -

here's my sample form:
http://smartbenefit.cjehost.com/export_form.php

i submit it (actions to my version of your code: export.php) and the data i've filled in for $filename outputs but nothing else - feel free to try it.

i need the code to send the excel file as an email attachment - please take a look at my version of your code below:


<?php require_once('Connections/connSmartBenefit.php'); ?>
<?php
$export='';
 
$Selectedvalue =$_POST["BackupCombo"];
$filename =$_POST["filename"];
$from = (!empty($_POST["from"])) ? $_POST["from"] : false;
$to = (!empty($_POST["from"])) ? $_POST["from"] : false;
 
//$to=$_POST["to"];
 
printf($filename);
//$datFrom =$from;
 
 
   // Convert to SQL format
   //$parts = explode("/", $datFrom);
   //$sqlDateFrom = $parts[2]."-".$parts[1]."-".$parts[0]; // 2009-08
//printf($sqlDateFrom);
//$datTo =$to;
//$parts = explode("/", $datTo);
  // $sqlDateTo = $parts[2]."-".$parts[1]."-".$parts[0];
//printf($datTO);                
 
if($Selectedvalue=="User"&&$from ==''&&$to =='')
{
$export.="<html>
<table border=1>
<tr bgcolor='#000000'>
        <th><font color=white>First Name</font></th>
        <th><font color=white>Last Name</font></th>
        <th><font color=white>Home Phone</font></th>
        <th><font color=white>Email Address</font></th>
</tr>"; 
mysql_select_db($database_connSmartBenefit, $connSmartBenefit);
$query=" Select * from users_cc";
 
$result = mysql_query($query, $connSmartBenefit) or die(mysql_error());
if(mysql_num_rows($result)>0) {
        while($row=mysql_fetch_array($result)){ 
$export.="<tr><td>".$row['First Name']."</td><td>".$row['Last Name']."</td><td>".$row['Home Phone']."</td><td>".$row['Email Address']."</td></tr>";
 
 
        }
}
 
 
$export.="</table>";
header("Content-type: application/ms-excel");
//header("Content-type: application/octet-stream");
header("Content-Disposition: inline; filename='$filename'");
header("Content-Description: PHP5 Generated Data" );
header("Content-Length: ".strlen($export));
print $export;
}
?>

Open in new window

I think EXCEL can read CSV files, and PHP has functions built-in for working with CSV, so I would be inclined to go that way.  Look up fputcsv() for a good example.

For ease in debugging, why not just write the CSV file to your server.  Then you can look at the output with a regular text editor.  You can use a "force download" script to present the CSV to another browser or application.

Just curious, is line #8 correct?

Best, ~Ray
Hi Ray - Let me explain exactly what I'm looking to do and why:

My simple contact form (first, last name, email address, phone number) is inserting data into a mysql db table. I need to then have that data imported into my constant contact list. The client does not want a simple email box that redirects to the constant contact form - which is usually how constant contact works. so, instead, i want either the form submission to be inserted into the mysql db table  AND sent to a specified email address as an attachment - csv is fine - the recipient of the email attachment will then import it into constant contact.

OK, that makes sense.  How many records are we talking about?  Is there any advantage or disadvantage to sending the same records more than one time?
the only disadvantage i see to sending the same records more than once (I'm assuming you're talking about sending the entire db table instead of just the latest record submitted) is that the larger the db table gets, the longer it will take to import into constant contact - that said, if it's less complicated to export the entire table - i'm all for that.  i don't see thse db tables getting much bigger than a few hundred records.
OK - a few hundred is easy to manage, even by hand if necessary. I am thinking that there is a risk of disconnect between the form input and the final repose of those records at Constant Contact, so I want to minimize that risk.

At our church we switched from our own email and began to use Constant Contact earlier this year; when the Director of communications gets back from lunch I will ask her about how we did the initial load of contacts, and what we do to sync up the lists (if anything).
Thanks Ray - I know how to import the contact ist into constant contact - tested it last night - i just need the compatible csv file to be send as an email attachment after a form is submitted.
phillystyle123, are you aware that CC has an API for doing this?

http://developer.constantcontact.com/doc/contactsCollection

"A new contact is created by making an HTTP POST to the collection URI. The POST body must contain an Atom entry element that includes the content for the new contact. The Content-Type of the request must be set to application/atom+xml."
thanks v2Media - this is totally new to me - where would i put this code:

<entry xmlns="http://www.w3.org/2005/Atom">
  <title type="text"> </title>
  <updated>2008-07-23T14:21:06.407Z</updated>
  <author></author>
  <id>data:,none</id>
  <summary type="text">Contact</summary>
  <content type="application/vnd.ctct+xml">
    <Contact xmlns="http://ws.constantcontact.com/ns/1.0/">
      <EmailAddress>test101@example.com</EmailAddress>
      <FirstName>First</FirstName>
      <LastName>Last</LastName>
      <OptInSource>ACTION_BY_CONTACT</OptInSource>
      <ContactLists>
        <ContactList id="http://api.constantcontact.com/ws/customers/joesflowers/lists/1" />
      </ContactLists>
    </Contact>
  </content>
</entry>
ASKER CERTIFIED SOLUTION
Avatar of v2Media
v2Media
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks! currently my form is inserting data into a mysql db table. which i'm using to manage passwords, etc. is there a way to use the constant contact code to add the contact info to constant contact AND ALSO AT THE SAME TIME insert the contact into my mysql db table?? does that make sense?
Sure. In the add_contact.php file, you'd add your db insert code after "if (!empty($_POST)) {" and before "$postFields = array();"
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also, you should probably correct line 57 to use the $to var instead of my GMail address ;-)

Cheers, ~Ray
wow - 2 completely different options! thanks to both of you for the help. i'm waitng to hear back from the client to test.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
v2Media - I'm taking a shot at using the api you referenced. I'm getting these errors:

Warning: Invalid argument supplied for foreach() in /home/cjehost/public_html/smartbenefit/api_test/cc_class.php on line 99

Warning: Invalid argument supplied for foreach() in /home/cjehost/public_html/smartbenefit/api_test/cc_class.php on line 121

here's the page:

http://smartbenefit.cjehost.com/api_test/add_contact.php

also, here's the code for cc_class.php
<?php 
 
/**
 
 * Class that is using REST to communicate with ConstantContact server
 
 * @author ConstantContact Dev Team
 
 * @version 1.0
 
 * @since 27.07.2009
 
 *
 
 */
 
class ConstantContact {
 
	
 
	//FROM HERE YOU MAY MODIFY YOUR CREDENTIALS
 
	var $login = 'phillystyle123'; //username for your account
 
	var $password = 'Schneken1'; //password for your account
 
	var $apikey = '6dc96c2c-74ae-4df3-a3e1-9e0fdfbbe7bc '; // Api Key for your account.
 
	
 
	var $curl_debug = false; //set this to true to see the response code returned by cURL
 
	
 
	// YOUR BASIC CHANGES SHOULD END RIGHT HERE
 
	// Usually, below this line shouldn't be done any modification.
 
	var $requestLogin; //this contains full authentication string.
 
	var $apiPath = 'https://api.constantcontact.com/ws/customers/'; //is used for server calls. 
 
	var $lastError = ''; // this variable will contain last error message (if any)
 
	
 
	var $doNotIncludeLists = array('Removed','Do Not Mail','Active'); //define which lists shouldn't be returned.
 
	var $actionBy = 'ACTION_BY_CUSTOMER'; // can be ACTION_BY_CUSTOMER or ACTION_BY_CONTACT
 
 
 
	public function __construct() {
 
		//when the object is getting initialized, the login string must be created as API_KEY%LOGIN:PASSWORD
 
		$this->requestLogin = $this->apikey."%".$this->login.":".$this->password;
 
		$this->apiPath = $this->apiPath.$this->login;		
 
	}
 
 
 
	/**
 
	 * Recursive Method that retrieves  all the Email Lists from ConstantContact.
 
	 *
 
	 * @param string $path [default is empty]
 
	 * @return array of lists 
 
	 */
 
	public function getLists($path='') {
 
		$mailLists = array();
 
		if (empty($path)) {
 
			$call = $this->apiPath.'/lists';
 
		}
 
		else {
 
			$call = $path;
 
		}
 
		$return = $this->doServerCall($call);
 
		$parsedReturn = simplexml_load_string($return);
 
		$call2 = '';
 
		foreach ($parsedReturn->link as $item) {
 
			$tmp = $item->Attributes();
 
			$nextUrl =  '';
 
			if ((string)$tmp->rel == 'next') {
 
				$nextUrl = (string)$tmp->href;
 
				$arrTmp = explode($this->login,$nextUrl);
 
				$nextUrl = $arrTmp[1];				
 
				$call2 = $this->apiPath.$nextUrl;
 
				break;
 
			}
 
		}
 
		foreach ($parsedReturn->entry as $item) {
 
			//Here we add to return list, only ContactLists that beginins with "test"
 
//			if (substr((string)$item->title,0,4) == 'test') {
 
//				$tmp = array();
 
//				$tmp['id'] = (string)$item->id;
 
//				$tmp['title'] = (string)$item->title;
 
//				$mailLists[] = $tmp;
 
//			}
 
			if (!in_array((string)$item->title,$this->doNotIncludeLists)) {
 
				$tmp = array();
 
				$tmp['id'] = (string)$item->id;
 
				$tmp['title'] = (string)$item->title;
 
				$mailLists[] = $tmp;
 
			}
 
		}
 
		if (empty($call2)) {
 
			return $mailLists;		
 
		}
 
		else {
 
			return array_merge($mailLists,$this->getLists($call2));
 
		}
 
	}
 
	
 
	/**
 
	 * Method that retrieves from ConstantContact a collection with all the Subscribers
 
	 * If email parameter is mentioned then only mentioned contact is retrieved.
 
	 * @param string $email
 
	 * @return Bi-Dimenstional array with information about contacts. 
 
	 */
 
	public function getSubcribers($email = '',$page = '') {
 
		$contacts = array();
 
		$contacts['items'] = array();
 
		
 
		if (!empty($email)) {
 
			$call = $this->apiPath.'/contacts?email='.$email;
 
		}
 
		else {
 
			if (!empty($page)) {
 
				$call = $this->apiPath.$page;
 
			}
 
			else {
 
				$call = $this->apiPath.'/contacts';
 
			}
 
		}
 
		$return = $this->doServerCall($call);
 
		$parsedReturn = simplexml_load_string($return);
 
		//we parse here the link array to establish which are the next page and previous page
 
		foreach ($parsedReturn->link as $item) {
 
			$attributes = $item->Attributes();
 
			if (!empty($attributes['rel']) && $attributes['rel']=='next') {
 
				$tmp = explode($this->login,$attributes['href']);
 
				$contacts['next'] = $tmp[1];			
 
			}
 
			if (!empty($attributes['rel']) && $attributes['rel']=='first') {
 
				$tmp = explode($this->login,$attributes['href']);
 
				$contacts['first'] = $tmp[1];			
 
			}
 
			if (!empty($attributes['rel']) && $attributes['rel']=='current') {
 
				$tmp = explode($this->login,$attributes['href']);
 
				$contacts['current'] = $tmp[1];			
 
			}
 
		}
 
		
 
		foreach ($parsedReturn->entry as $item) {
 
			$tmp = array();
 
			$tmp['id'] = (string)$item->id;
 
			$tmp['title'] = (string)$item->title;
 
			$tmp['status'] = (string)$item->content->Contact->Status;
 
			$tmp['EmailAddress'] = (string)$item->content->Contact->EmailAddress;
 
			$tmp['EmailType'] = (string)$item->content->Contact->EmailType;
 
			$tmp['Name'] = (string)$item->content->Contact->Name;
 
			
 
			$contacts['items'][] = $tmp;
 
		}
 
		return $contacts;
 
	}
 
	
 
	/**
 
	 * Retrieves all the details for a specific contact identified by $email.
 
	 *
 
	 * @param string $email
 
	 * @return array with all information about the contact.
 
	 */
 
	public function getSubscriberDetails($email) {
 
		$contact = $this->getSubcribers($email);
 
		$fullContact = array();
 
		$call = str_replace('http://', 'https://', $contact['items'][0]['id']); // Convert id URI to BASIC compliant
 
		$return = $this->doServerCall($call);
 
		
 
		$parsedReturn = simplexml_load_string($return);
 
				
 
		$fullContact['id'] = $parsedReturn->id;		
 
   		$fullContact['email_address'] = $parsedReturn->content->Contact->EmailAddress;
 
   		$fullContact['first_name'] = $parsedReturn->content->Contact->FirstName;
 
   		$fullContact['last_name'] = $parsedReturn->content->Contact->LastName;
 
   		$fullContact['middle_name'] = $parsedReturn->content->Contact->MiddleName;
 
   		$fullContact['company_name'] = $parsedReturn->content->Contact->CompanyName;
 
   		$fullContact['job_title'] = $parsedReturn->content->Contact->JobTitle;
 
   		$fullContact['home_number'] = $parsedReturn->content->Contact->HomePhone;
 
   		$fullContact['work_number'] = $parsedReturn->content->Contact->WorkPhone;
 
   		$fullContact['address_line_1'] = $parsedReturn->content->Contact->Addr1;
 
   		$fullContact['address_line_2'] = $parsedReturn->content->Contact->Addr2;
 
   		$fullContact['address_line_3'] = $parsedReturn->content->Contact->Addr3;
 
   		$fullContact['city_name'] = (string)$parsedReturn->content->Contact->City;
 
   		$fullContact['state_code'] = (string)$parsedReturn->content->Contact->StateCode;
 
   		$fullContact['state_name'] = (string)$parsedReturn->content->Contact->StateName;
 
   		$fullContact['country_code'] = $parsedReturn->content->Contact->CountryCode;
 
   		$fullContact['zip_code'] = $parsedReturn->content->Contact->PostalCode;
 
   		$fullContact['sub_zip_code'] = $parsedReturn->content->Contact->SubPostalCode;
 
   		$fullContact['custom_field_1'] = $parsedReturn->content->Contact->CustomField1;
 
   		$fullContact['custom_field_2'] = $parsedReturn->content->Contact->CustomField2;
 
   		$fullContact['custom_field_3'] = $parsedReturn->content->Contact->CustomField3;
 
   		$fullContact['custom_field_4'] = $parsedReturn->content->Contact->CustomField4;
 
   		$fullContact['custom_field_5'] = $parsedReturn->content->Contact->CustomField5;
 
   		$fullContact['custom_field_6'] = $parsedReturn->content->Contact->CustomField6;
 
   		$fullContact['custom_field_7'] = $parsedReturn->content->Contact->CustomField7;
 
   		$fullContact['custom_field_8'] = $parsedReturn->content->Contact->CustomField8;
 
   		$fullContact['custom_field_9'] = $parsedReturn->content->Contact->CustomField9;
 
   		$fullContact['custom_field_10'] = $parsedReturn->content->Contact->CustomField10;
 
   		$fullContact['custom_field_11'] = $parsedReturn->content->Contact->CustomField11;
 
   		$fullContact['custom_field_12'] = $parsedReturn->content->Contact->CustomField12;
 
   		$fullContact['custom_field_13'] = $parsedReturn->content->Contact->CustomField13;
 
   		$fullContact['custom_field_14'] = $parsedReturn->content->Contact->CustomField14;
 
   		$fullContact['custom_field_15'] = $parsedReturn->content->Contact->CustomField15;
 
   		$fullContact['notes'] = $parsedReturn->content->Contact->Note;
 
   		$fullContact['mail_type'] = $parsedReturn->content->Contact->EmailType;   		
 
   		$fullContact['status'] = $parsedReturn->content->Contact->Status;
 
   		
 
   		$fullContact['lists'] = array();
 
		if($parsedReturn->content->Contact->ContactLists->ContactList){
 
   		foreach ($parsedReturn->content->Contact->ContactLists->ContactList as $item) {
 
   			$fullContact['lists'][] = trim((string)$item->Attributes());   			
 
   		}
 
		}
 
		return $fullContact;   		
 
		
 
	}
 
	
 
	/**
 
	 * Method that modifies a contact State to DO NOT MAIL
 
	 *
 
	 * @param string $email - contact email address
 
	 * @return TRUE in case of success or FALSE otherwise
 
	 */
 
	public function deleteSubscriber($email) {
 
		if (empty($email)) {
 
			return false;	
 
		}
 
		$contact = $this->getSubcribers($email);
 
		$id = $contact['items'][0]['id'];
 
		$return = $this->doServerCall($id,'','DELETE');
 
		if (!empty($return)){
 
			return false;
 
		}
 
		return true;
 
	}
 
	
 
	/**
 
	 * Method that modifies a contact State to REMOVED
 
	 *
 
	 * @param string $email - contact email address
 
	 * @return TRUE in case of success or FALSE otherwise
 
	 */
 
	public function removeSubscriber($email) {
 
		$contact = $this->getSubscriberDetails($email);
 
		$contact['lists'] = array();
 
		$xml = $this->createContactXML($contact['id'],$contact);
 
		if ($this->editSubscriber($contact['id'],$xml)) {
 
			return true;
 
		}
 
		else {
 
			return false;
 
		}
 
	}
 
	
 
	/**
 
	 * Upload a new contact to ConstantContact server
 
	 *
 
	 * @param strong $contactXML - formatted XML with contact information
 
	 * @return TRUE in case of success or FALSE otherwise
 
	 */
 
	public function addSubscriber($contactXML) {
 
		$call = $this->apiPath.'/contacts';
 
		$return = $this->doServerCall($call, $contactXML, 'POST');
 
		$parsedReturn = simplexml_load_string($return);
 
		if($return) {
 
			return true; 
 
		} else {
 
		 $this->lastError = 'An Error Occurred';
 
			return false; 
 
		}
 
		
 
	}
 
	
 
	/**
 
	 * Modifies a contact
 
	 *
 
	 * @param string $contactUrl - identifies the url for the modified contact
 
	 * @param string $contactXML - formed XML with contact information
 
	 * @return TRUE in case of success or FALSE otherwise
 
	 */
 
	public function editSubscriber($contactUrl, $contactXML) {
 
		$return = $this->doServerCall($contactUrl, $contactXML, 'PUT');
 
		if (!empty($return)) {
 
			if (strpos($return,'<')!== false) {
 
				$parsedReturn = simplexml_load_string($return);
 
				if(!empty($parsedReturn->message)) {
 
					$this->lastError = $parsedReturn->message;
 
				}
 
			}
 
			else {
 
				$this->lastError = $parsedReturn->message;
 
			}
 
			return false;
 
		}
 
		return true;
 
	}
 
	
 
	/**
 
	 * Method that compose the needed XML format for a contact
 
	 *
 
	 * @param string $id
 
	 * @param array $params
 
	 * @return Formed XML
 
	 */
 
	public function createContactXML($id, $params = array()) {
 
		
 
		if (empty($id)) {
 
			$id = "urn:uuid:E8553C09F4xcvxCCC53F481214230867087";
 
		}
 
		$update_date = date("Y-m-d").'T'.date("H:i:s").'+01:00';
 
		
 
		
 
        $xml_string = "<entry xmlns='http://www.w3.org/2005/Atom'></entry>";
 
   		$xml_object = simplexml_load_string($xml_string);
 
 
 
   		$title_node = $xml_object->addChild("title", htmlspecialchars("TitleNode"));
 
   		$updated_node = $xml_object->addChild("updated", htmlspecialchars($update_date));
 
   		
 
   		$author_node = $xml_object->addChild("author");
 
   		$author_name = $author_node->addChild("name", htmlspecialchars("CTCT Samples"));
 
   		
 
   		$id_node = $xml_object->addChild("id", $id);
 
 
 
   		$summary_node = $xml_object->addChild("summary", htmlspecialchars("Customer document"));
 
   		$summary_node->addAttribute("type", "text");
 
   		$content_node = $xml_object->addChild("content");
 
   		$content_node->addAttribute("type", "application/vnd.ctct+xml");
 
 
 
   		
 
   		$contact_node = $content_node->addChild("Contact", htmlspecialchars("Customer document"));
 
   		$contact_node->addAttribute("xmlns", "http://ws.constantcontact.com/ns/1.0/");
 
   		
 
   		$email_node = $contact_node->addChild("EmailAddress", urldecode(htmlspecialchars($params['email_address'])));
 
   		$fname_node = $contact_node->addChild("FirstName", urldecode(htmlspecialchars($params['first_name'])));
 
   		$lname_node = $contact_node->addChild("LastName", urldecode(htmlspecialchars($params['last_name'])));
 
   		$lname_node = $contact_node->addChild("MiddleName", urldecode(htmlspecialchars($params['middle_name'])));
 
   		$lname_node = $contact_node->addChild("CompanyName", urldecode(htmlspecialchars($params['company_name'])));
 
   		$lname_node = $contact_node->addChild("JobTitle", urldecode(htmlspecialchars($params['job_title'])));
 
 
 
   		if ($params['status'] == 'Do Not Mail') {
 
   			$this->actionBy = 'ACTION_BY_CONTACT';
 
   		}
 
		$optin_node = $contact_node->addChild("OptInSource", htmlspecialchars($this->actionBy));
 
   		
 
   		$hn_node = $contact_node->addChild("HomePhone", htmlspecialchars($params['home_number']));
 
   		$wn_node = $contact_node->addChild("WorkPhone", htmlspecialchars($params['work_number']));
 
   		$ad1_node = $contact_node->addChild("Addr1", htmlspecialchars($params['address_line_1']));
 
   		$ad2_node = $contact_node->addChild("Addr2", htmlspecialchars($params['address_line_2']));
 
   		$ad3_node = $contact_node->addChild("Addr3", htmlspecialchars($params['address_line_3']));
 
   		$city_node = $contact_node->addChild("City", htmlspecialchars($params['city_name']));
 
   		$state_node = $contact_node->addChild("StateCode", htmlspecialchars($params['state_code']));
 
   		$state_name = $contact_node->addChild("StateName", htmlspecialchars($params['state_name']));
 
   		$ctry_node = $contact_node->addChild("CountryCode", htmlspecialchars($params['country_code']));
 
   		$zip_node = $contact_node->addChild("PostalCode", htmlspecialchars($params['zip_code']));
 
   		$subzip_node = $contact_node->addChild("SubPostalCode", htmlspecialchars($params['sub_zip_code']));
 
   		$note_node = $contact_node->addChild("Note", htmlspecialchars($params['notes']));
 
   		$emailtype_node = $contact_node->addChild("EmailType", htmlspecialchars($params['mail_type']));
 
       	
 
       	if (!empty($params['custom_fields'])) {
 
	       	foreach($params['custom_fields'] as $k=>$v) {	       			
 
	       			$contact_node->addChild("CustomField".$k, htmlspecialchars($v));
 
	       	}
 
       	}
 
       	
 
		$contactlists_node = $contact_node->addChild("ContactLists");
 
   		
 
		if($params['lists']){
 
		foreach ($params['lists'] as $tmp) {		
 
			$contactlist_node = $contactlists_node->addChild("ContactList");
 
   			$contactlist_node->addAttribute("id", $tmp);
 
		}
 
		}
 
		$entry = $xml_object->asXML();			
 
 
 
		return $entry;    		
 
	}
 
	
 
	/**
 
	 * Method that returns a list with all states found on states.txt file 
 
	 *
 
	 * @return array with state codes and state names
 
	 */
 
	public function getStates() {
 
		$returnArr = array();
 
		$lines = file("states.txt");
 
		foreach ($lines as $line) {
 
			$tmp = explode(" - ",$line);
 
			if (sizeof($tmp) == 2) {
 
				$returnArr[trim($tmp[1])] = trim($tmp[0]);
 
			}
 
		}
 
		return $returnArr;
 
	}
 
	
 
	/**
 
	 * Returns a list with all countries found on countries.txt file
 
	 *
 
	 * @return array with country codes and country names
 
	 */
 
	public function getCountries() {
 
		$returnArr = array();
 
		$lines = file("countries.txt");
 
		foreach ($lines as $line) {
 
			$tmp = explode(" - ",$line);
 
			if (sizeof($tmp) == 2) {
 
				$returnArr[trim($tmp[1])] = trim($tmp[0]);
 
			}
 
		}
 
		return $returnArr;
 
	}
 
	
 
	/**
 
	 * Private function used to send requests to ConstantContact server
 
	 *
 
	 * @param string $request - is the URL where the request will be made
 
	 * @param string $parameter - if it is not empty then this parameter will be sent using POST method
 
	 * @param string $type - GET/POST/PUT/DELETE
 
	 * @return a string containing server output/response  
 
	 */
 
	private function doServerCall($request, $parameter = '', $type="GET") {				
 
		
 
		$ch = curl_init();
 
		$request = str_replace('http://', 'https://', $request); // Convert id URI to BASIC compliant
 
		curl_setopt ($ch, CURLOPT_URL, $request);
 
		curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
 
        curl_setopt ($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
 
        curl_setopt ($ch, CURLOPT_USERPWD, $this->requestLogin);
 
        // curl_setopt ($ch, CURLOPT_FOLLOWLOCATION  ,1); 
 
		curl_setopt ($ch, CURLOPT_HEADER, 0);
 
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 
        curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type:application/atom+xml"));
 
		
 
		curl_setopt ($ch, CURLOPT_FAILONERROR, 1);
 
		curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
 
		switch ($type) {
 
			case 'POST': 
 
				curl_setopt ($ch, CURLOPT_POST, 1);
 
				curl_setopt ($ch, CURLOPT_POSTFIELDS , $parameter);								
 
				break;
 
			case 'PUT':
 
				$tmpfile = tmpfile();
 
				fwrite($tmpfile, $parameter);
 
				fseek($tmpfile, 0);				
 
				curl_setopt($ch, CURLOPT_INFILE, $tmpfile); 
 
				curl_setopt($ch, CURLOPT_PUT, 1);
 
				curl_setopt($ch, CURLOPT_INFILESIZE, strlen($parameter));
 
				fclose($tmpfile); 
 
				
 
				break;
 
			case 'DELETE':
 
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");				
 
				break;
 
			default:
 
				curl_setopt ($ch, CURLOPT_GET, 1);
 
				break;
 
		}
 
		
 
		$emessage = curl_exec ($ch);
 
		// echo $request.'<br />';
 
		if($this->curl_debug){ echo $error = curl_error($ch); }
 
		curl_close ($ch);
 
		//if($emessage){ $return = array('return' => true, 'body' => $emessage); }
 
		//else { $return = array('return' => false, 'body' => $error); }
 
		
 
		
 
		return $emessage; # This returns HTML
 
		
 
						
 
	}
 
 
 
}
 
 
 
 
 
 
 
?>

Open in new window

A bit tricky here - I ended up using the API - the reason i was getting the foreach() error is because there was a space between the last api key character and the single quote. Ray - I'm fairly sure I'll end up using your method as well at some point with this client. Thanks to you both for the help!!!

philystyle