fetch file data from ftp & process in php - php

I have the below script to import data from a csv file on my ftp server, the script works correctly.
$ftp_server = '---Domain---';
$ftp_user_name = '---Uname---';
$ftp_user_pass = '---pass---';
// open some file for reading
$csvfile = '/home/domain/public_html/myfolder/user.csv';
if(!file_exists($csvfile))
{
echo "File not found. Make sure you specified the correct path.\n";
exit;
}
else
{
echo "File exist on this path.\n";
}
user.csv
Email Fname lname
------------------------------
mark#gmail.com mark martin
allan#gmail.com allan lee
I want to fetch data from csv file & pass to php function which will process that data with DB
i.e. add-update user information
I am not getting how to fetch data & pass to function
Any assistance will be appreciated.
Thanks.

$a=array();
$file = fopen('user.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
array_push($a,$line);
}
fclose($file);
//you will get all the content in array $a, you can ride array by using foreach

<?php
$csvfile = '/home/domain/public_html/myfolder/user.csv';
if (($handle = fopen($csvfile, "r")) !== FALSE) {
while (($line = fgetcsv($handle, 0, ",")) !== FALSE) {
// do whatever processing you need with $line array
}
fclose($handle);
}
This solution will give you csv data line by line. If you need all data from csv to an array Use #user1844933's solution

Related

Read a tabulator seperated csv with PHP

I'm not able to read a tabulator seperarated csv file (and yes, i know its csv and no tsv and the c is for tabulator...) with php and seperate it right. When i give out my imported Data with echo or readfile all the tabulators are replaced by a space and i can't use space as a sperator.
Actually i'm a bit confused that this problem is not very common when i use Google, so maybe i'm the problem...
The Problem exists with XAMPP v3.2.3 and PHP Version 7.3.5
$tempFile = fopen($tempFilePath, "r");
$uploadData = fread($tempFile, filesize($tempFilePath));
fclose($tempFile);
echo $uploadData;
$uploadData = str_replace('"','',$uploadData);
$uploadData = str_replace('\r\n','\n',$uploadData);
$uploadData = str_replace('\r','\n',$uploadData);
$uploadData = str_replace(';',',',$uploadData);
$uploadData = str_replace('\t',',',$uploadData); //Here i'm trying to replace the tabulator with a colon to work with it afterwards
When reading a CSV file in PHP, it is best to use the fgetcsv function. With it you can specify the deliminator of the file. The function will output a row of the file. Your deliminator should be "\t".
You should use fgetcsv function which already has functionality to read tsv.
Like this:
$uploadData = [];
if (($handle = fopen("test.csv", "r")) !== false) {
while (($data = fgetcsv($handle, 0, "\t")) !== false) {
$uploadData[] = $data;
}
fclose($handle);
}
If you want to convert tsv to csv you can use inverse function fputcsv:
$fh = fopen('file.csv');
foreach ($uploadData as $datum) {
fputcsv($fh, $datum);
}
fclose($fh);
If you want automatically detect csv delimiter maybe this article can help you.

similar to simplexml_load_file but for csv in php

When a client upload an xml file, the following piece of code catch it "on the fly", and perform several operations without actually saving the file in the server (just a temp file I guess):
if(isset($_POST['AddXmlElement'])) {
$xml = simplexml_load_file($_FILES['NewRecordXml']['tmp_name']);
foreach( $xml->records->record as $key1) {
//Do stuff;
}
}
I would like to do the same, but with a csv file. Is there an instruction like "simplecsv_load_file" that can be used?
Consider using fopen() to open a read connection on the csv upload:
$handle = fopen($_FILES["csvfile"]["tmp_name"], "r");
// LOOP ITERATES THROUGH ALL ROWS OF CSV FILE
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo $data[0]; // FIRST COMMA-SEPARATED CONTENT
echo $data[1]; // SECOND COMMA-SEPARATED CONTENT
...
}
fclose($handle);

PHP Cron Read CSV from URL and Convert to Array

I am trying to develop email system that need to be send every month. So i need to build cron job file from php. Anyone know how to read file CSV or Excel file from url such as:
http://yourdomain.com/cron.php?file=http://google.com/monthly.csv
I am stuck when try to read file from url.
This is my recent code:
<?php
$url = 'http://www1.intranet.com/reportingtool.asp?settings=var&export=ok';
$tmpfname = tempnam(sys_get_temp_dir());
file_put_contents(
$tmpfname,
file_get_contents($url)
);
?>
If you're dealing with remote files, you should always keep in mind that
The connection between you and the remote can break, and you won't get the full file content;
The file can be too big to read it on-the-fly.
In both cases, file_get_contents() is not a very good thing to use: you should consider cURL functions for that. However, if the concerns above are negligible, you should be okay with the following (as the example here suggests):
$url = 'http://www1.intranet.com/reportingtool.asp?settings=var&export=ok';
$tmpfname = tempnam(sys_get_temp_dir());
file_put_contents(
$tmpfname,
file_get_contents($url)
);
if (($handle = fopen($tmpfname, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
// Do something with $data, which comes in
// as an array of values from the current CSV line.
}
}
Someone would need one more example, so leaving it here:
$dataSource can be any file on drive or just online link to parse csv.
private array $data = [];
private string $dataSource = "https://any.csv";
if (($open = fopen($dataSource, 'rb')) !== false)
{
while (($data = fgetcsv($open, 1000, ";")) !== false)
{
$data[] = $data;
}
fclose($open);
}

PHP Formatting A Column (dollar sign) In csv Upload Script

I have a script that uploads a csv file with 3 columns (phone, name, amount). The script removes any formatting on the phone, ie; ()- and puts the file on the server. The amount column in the file shows the amount like 125.00 and I need it to show $125.00. Any help would be much appreciated.
$file_destination = '/****/****/****/***/' . $file_name_new;
$contents = file_get_contents($file_tmp);
$contents = str_replace("(","",$contents);
$contents = str_replace(")","",$contents);
$contents = str_replace("-","",$contents);
file_put_contents($file_tmp, $contents);
if(move_uploaded_file($file_tmp, $file_destination)) {
Whether you want to reformat the values strictly for output or store the new formatted data in your CSV file, it's probably going to be more effective to use fgetcsv and fputcsv. Those functions are designed for properly reading in and writing out CSV formatted files.
Example
$rows = [];
if (($handle = fopen($file_tmp, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
list($phone, $name, $amount) = $data;
$phone = str_replace(['(',')','-'], '', $phone);
$amount = sprintf('$%.2f', $amount);
// you can build a new array with the updated values
$rows[] = [$phone, $name, $amount];
// or output directly
echo "$phone | $name | $amount";
}
fclose($handle);
}
// if you want to save the destination with the updated information...
$fp = fopen($file_destination, 'w');
foreach ($rows as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);

Read .csv file and save its values in a list of arrays

I am new at php programming but I have been stuck with this code for some time.
I would like to read a .csv file line by line and then save its values in a list of arrays.
$file = fopen('Sub-Companies.csv', 'r');
while (($line =
fgetcsv($file)) !== FALSE) {
print_r($line);
list($customer_id[],$company_name[],$department[],$employee[],$country[],$zipcode[],$address[],$city[],
$smth1[], $smth2[], $phone_no1[],$phone_no2[],$email[],$website[],
$customer_no[],$problem1[],$problem2[]) = explode(";",$line); }
fclose($file); var_dump($customer_id);
The problem is that, although it is read correctly the file, then the explode is not working and the arrays appear to be null.
One thing that I am considering is that some arrays have more ";" than others, so that might be a problem, that is why I have the arrays $problem1 and $problem2, in order to store the values of this arrays.
Any help would be great!
You're using fgetcsv() in the wrong way.
We've come to this solution while chatting here on StackOverflow.
<?php
// Create file data.csv with your data
$handle = fopen('Sub-Companies.csv', 'r');
$customer_id = array();
$xyz_array = array();
// ...
// Better use a specified length (second parameter) instead of 0
// It slows down the whole process of reading the data!
while (($line = fgetcsv($handle, 0, ';')) !== FALSE) {
$customer_id[] = $line[0];
$xyz_array[] = $line[1];
}

Categories