We currently open a csv from our server and then do some stuff with the data like this:
$CSVfile = fopen('filename.csv', "r");
if($CSVfile !== FALSE) {
$count = 0;
while(! feof($CSVfile)) {
$data = fgetcsv($CSVfile, 5000, ",");
if ($count > 0 && !empty($data)) {
// Do something
}
}
}
We need to change the system as the file will now be hosted on an external server so we need to SFTP into it to retrieve the file. I've installed phpseclib and got the connection working but it just keeps echoing the file contents on the screen. I have it set up like this:
include 'vendor/autoload.php';
$sftp = new \phpseclib\Net\SFTP('SERVER');
if (!$sftp->login('USERNAME', 'PASSWORD')) {
exit('Login Failed');
} else {
$file = $sftp->fetch('FILE_LOCATION');
}
$CSVfile = fopen($file, "r");
if($CSVfile !== FALSE) {
$count = 0;
while(! feof($CSVfile)) {
$data = fgetcsv($CSVfile, 5000, ",");
if ($count > 0 && !empty($data)) {
// Do Something
}
}
}
How do I get the new system to read the file contents and do something with it rather than just showing all the file contents?
As @verjas commented already, there's no fetch
method in phpseclib.
If you want to download a file to a string, use SFTP::get
:
$contents = $sftp->get("/remote/path/file.csv");
You can then use str_getcsv
to parse the contents. According to a contributed note at the function documentation, this should do:
$data = str_getcsv($contents, "\n"); // parse the rows
foreach ($data as $line)
{
$row_data = str_getcsv($line); // parse the items in rows
}