Here is a small script that will allow you to dump any object to a CSV file.
PHP Code:
<?php
ini_set("soap.wsdl_cache_enabled", "0");
require_once ('./includes/soapclient_new/SforcePartnerClient.php');
$date = date("mdy-hia");
$file = "datadump-$date.csv";
//Salesforce Connection information
$wsdl = './includes/soapclient_new/partner.wsdl.xml';
$userName = "user";
$password = "pass";
//setup connection
$client = new SforcePartnerClient();
$client->createConnection($wsdl);
$loginResult = $client->login($userName, $password);
//SOQL query for Object in Salesforce
$soql = "Select Id, LastName, FirstName, Email FROM Contact";
//Processes the query to get account information from Salesforce
$records = get_records($client, $soql);
if ($records === false)
{
mail("me@email.com", "PHP Lead Export Script Error", "There has been an error in the Lead replication script\nPlease Check Script");
}
function get_records($connection, $query)
{
//Set this to the number of records to process per batch
//200 is the minimum
$queryOptions = new QueryOptions(1000);
$connection->setQueryOptions($queryOptions);
$response = $connection->query(($query), $queryOptions);
if ($response->size > 0)
{
$records = $response->records;
// Cycles through additional responses if the number of records// exceeds the batch size
$count_records = 0;
while (!$response->done)
{
$records = $response->records;
set_time_limit(100);
ini_set("memory_limit", "512M");
//Process curent $records
$current_count = csv_dump($records, false);
if ($current_count === false)
{
return false;
}
else
{
$count_records += $current_count;
}
$response = $connection->queryMore($response->queryLocator, $queryOptions);
}
set_time_limit(100);
$records = $response->records;
$current_count = csv_dump($records, true);
if ($current_count === false)
{
return false;
}
else
{
$count_records += $current_count;
}
}
return $count_records;
}
function csv_dump($data, $header = false)
{
global $file;
$fp = fopen($file, 'a');
foreach ($data as $r)
{
$pass_this['id'] = $r->Id;
foreach ($r->fields as $key => $value)
{
$pass_this[$key] = $r->fields->$key;
}
//Uncomment this to see array in browser
//echo '<pre>' . print_r($pass_this, true) . '</pre>';
if ($header)
{
$keys = array_keys($pass_this);
fputcsv($fp, $keys);
$header = false;
}
fputcsv($fp, $pass_this);
echo "record added to CSV<br />";
flush();
}
}
?>
Things to add or that could be added
- You could set this up to download the document
- you could set this to FTP the CSV to a certain place
- you could set this to email the script (not a good suggestion because of size issues)
- you could add a get parameter to run various objects like csv_dump.php?object=Account
Anyway some may find it useful, some could probably not care that much
~Mike
Bookmarks