June 4, 2009
Integrating with Web1.0 Service Providers
The modern concept of ‘web services’ has always existed in one form or another. Originally the protocols were binary and incredibly complex to integrate, but times have changed a lot. However, there are still large swathes of service providers who provide web-based APIs, but only support primitive versions of these- relying on ‘file drops’ and simple callbacks. Worse still, these providers are particularly resistant to changing their ways. This can be a serious bar of entry for more modern development companies who are used to a SOAP/REST based system, stopping them climb the supplier chain.
This short example shows how you can use PHP to integrate with a supplier who insists on using a file drop mechanism – in this case, to get your date-stampped CSV files, prefixed “file-” wrapped up in ZIP file using the format user-DMY, on an FTP site of their choice!
$host='www.example.com';
$user='myuser';
$pass='mypass';
$date=date('dmy');
// where to store file
$store='/tmp/files.zip';
// get file
$ch = curl_init('ftp://{$user}:{$pass}@{$host}/{$user}-{$date}.zip');
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$file=curl_exec($ch);
file_put_contents($store,$file);
// output ids of all entries
$entries = getEntriesFromCSV(getEntryFile($store) );
foreach($entries as $entry){
print '{$entry['id']}\n';
}
/*
* @desc Get CSV number file from local ZIP file
* @author Leo Brown
* @param $file String Local file to open
*/
function getEntryFile($file)
{
if ($file &
&
is_resource($zip = zip_open($file))) {
while ($entry=zip_read($zip)) {
if ('file' == substr(zip_entry_name($entry),0,4)) {
return zip_entry_read($entry, zip_entry_filesize($entry
)
);
}
}
}
}
/*
* @desc Get provider entries from CSV formatted string
* @author Leo Brown
* @param $file String Allocated entries as 'entry,t1,t2,t3\n'
*/
function getEntriesFromCSV($file)
{
$lines=explode('\n',$file);
$entries=array();
foreach($lines as $line){
$fields=explode(',',trim($line));
if (is_numeric($fields[0])) {
$entry=array('id'=>$fields[0],
'data1'=>@$fields[1],
'data2'=>@$fields[2],
'data3'=>@$fields[3]
);
$entry[$fields[0]]=array_filter($entry);
}
}
return $entries;
}
?>