php - converting csv into array using str_get_csv without physically uploading - php

I'm just trying to upload a csv file and convert it to an array.
I've read on a previous post here that you can use str_getcsv() without having to physically upload the csv file to the server.
Is this correct or do I have to store the file somewhere first before I can run str_getcsv() and then delete it afterwards?
Here's my simple code at the moment (I'm using php 5.3):
if (isset($_POST['file_upload'])){
$csv = str_getcsv($_POST['csvfile']);
echo '<pre>';
print_r($csv);
echo '</pre>';
}

You should use $_FILES array to check file upload.
Use this code:
if(isset($_FILES["csvfile"])) {
$csv=str_getcsv(file_get_contents($_FILES["csvfile"]["tmp_name"]));
echo '<pre>';
print_r($csv);
echo '</pre>';
}

By default the file is stored in a temp directory which can be accessed by $_FILES['file_name']['tmp_name']:
As you can see, the first parameter of str_getcsv method must be a string and for this you can use file_get_contents
$csv = str_getcsv(file_get_contents($_FILES['csvfile']['tmp_name']));

If you are submitting a file (using <input type="file">), you will need to use move_uploaded_file(). The file is already on disk (if the form submit was succesful), you just need to move it. In this case, it is most convenient to use fgetcsv() which opens the file and parses it into arrays as you go (see the example in the documentation for that function).
If you are not submitting a file but a text using, for example, <textarea></textarea>, then you do not have to write the string in the $_POST variable to disk but can use str_getcsv to parse the string into an array.

Related

php read csv data as a string

Is there a function in php that lets you read a csv and return a string as it is.
I am aware of functions like fgetcsv etc that reads the csv and returns an array. But I was wondering if there is a way to get the full string as it is.
You must use the file_get_contents function
$data = file_get_contents('http://absoluteUrl');
or
$data = file_get_contents('local url');
Instead, to obtain an array of csv's lines use the file function.
You could use the file function:
$file = file("somefile.csv")
The you have every line in the variable file:
$file[0] = Firstline, aso.

comma separated in text file in php

if(isset($_POST['submit']))
{
$file = $_FILES['file']['name'];
$fh = fopen($file,'r+');
// string to put username and passwords
$users = '';
while(!feof($fh)) {
$user = explode(' ',fgets($fh));
foreach ($user as $value)
{
$number= rand(1000,10000);
$final_number[] = $value .','. $number;
}
}
//print_r($final_number);
file_put_contents($_FILES['file']['name'], $final_number);
}
this is my code for appending a random text to a string with comma and save it in text file but when i am saving it it is not saving properly after comma it is going to next line which should not happen plzz.. help me
Your code starts with a very big issue: you try to open and read from a file that, most probably, doesn't exist.
$file = $_FILES['file']['name'];
$fh = fopen($file,'r+');
As you can read in the documentation, assuming that your form contains an input element of type file having the name file, $_FILES['file']['name'] is the original name of the uploaded file, on the user's computer. It is only the name and it is not the name of the file on the server. It is provided just as a hint for the file's content (check the filename extension) but you cannot rely on it.
The content of the file is temporarily stored on the webserver in a file whose path can be found in $_FILES['file']['tmp_name']. You should pass it to the PHP function is_uploaded_file() to be sure the file was uploaded and your script is not the victim of an injection attempt then, if you need to keep it, use move_uploaded_file() to move it where you need. If you don't move it, when your script ends the temporary file is deleted.
Another problem of your code is on the lines:
$user = explode(' ',fgets($fh));
foreach ($user as $value)
As explained in the documentation, the function fgets() called without a second argument reads a line from the input file, including the newline character that ends it. Since you split the line into words I think you don't need the newline character. You can remove it by using trim() with the string returned by fgets() before passing it to explode().
The last issue of the code is:
file_put_contents($_FILES['file']['name'], $final_number);
Because $final_number is an array1, file_put_contents() joins its elements to get a string and writes the string into file. This operation concatenates the random value generated for a $value with the next $value and there is no way to tell which is which after the data is stored in the file. You probably need to keep them on separate lines. Use function implode() on $final_number, with "\n" as its first argument and write the generated string into the file instead.
The last one: don't write the generated content to $_FILES['file']['name']. It is not safe! It contains a string received from the browser; a malicious user can put whatever path they want there and your script will overwrite a file that it shouldn't change.
Create a directory dedicated to store files generated by your code and generate filenames based on an always incremented counter (the current time() or microtime() f.e.) for the files you store there. Never trust the data you receive from the browser.
1 $final_number is used as $final_number[] = ... and, because it is not defined when this line of code is executed for the first time, PHP creates an empty array for you and stores it in $final_number. Don't rely on this feature. Always initialize your variables before their first use. Put $final_number = array(); before the while().
I am going to use a different approach than you, let's say that the data you want to save to the file is stored in the variable $data.
So to append this data to the file with a comma at first, we can use just two lines of code:
$previousFileContent = file_get_contents("filename.txt");
file_put_contents("filename.txt", trim($previousFileContent . "," . $data));

How to extract data from CSV with PHP

I'm using the Sebastian Bergmann PHPUnit selenium webdriver.
Current I have:
$csv = file_get_contents('functions.csv', NULL,NULL,1);
var_dump($csv);
// select 1 random line here
This will load my CSV file and give me all possible data from the file.
It has multiple rows for example:
Xenoloog-FUNC/8_4980
Xylofonist-FUNC/8_4981
IJscoman-FUNC/8_4982
Question: How can I get that data randomly?
I just want to use 1 ( random) line of data.
Would it be easier to just grab 1 (random) line of the file instead of everything?
Split the string into an array, then grab a random index from that array:
$lines = explode("\n", $csv);
$item = $lines[array_rand($lines)];
You could use the offset and maxlen parameters to grab part of the file using file_get_contents. You could also use fseek after fopen to select part of a file. These functions both take numbers of bytes as arguments. This post has a little more information:
Get part of a file by byte number in php
It may require some hacking to translate a particular row-index of a CSV file to a byte offset. You might need to generate and load a small meta-data file which contains a list of bytes-occupancies for each row of of CSV data. That would probably help.

How to read a PHP file as text file to an array?

Here is my situation.Supposing I have a PHP file named as:
myfunctions.php
Is it possible to read the contents of that PHP file (myfunctions.php) in another script using available PHP functions?
I'm using the following functions without success in reading this PHP file:
file_get_contents()
file()
It simply returned blank. One of the possible successful method was to read this PHP file as text file but I do not know how to do this..If someone has some other methods, please share. Ideally I want the output to be an array so the data I would like to obtain will be easily manipulated for use.
Thanks.
If I were you, I will change the extension on the "myfunctions.php" to "myfunctions.txt" and use the theses functions
file_get_contents()
file()
But I don't know if you are allow to change the name of the document.
file() - Reads entire file into an array
fgets() - Gets line from file pointer
fread() - Binary-safe file read
readfile() - Outputs a file
file_put_contents() - Write a string to a file
stream_get_contents() - Reads remainder of a stream into a string
stream_context_create() - Creates a stream context
You need fread. To put it into an array, you might look at explode

successively loading a folder full of csv files without naming using a php script in Mac Terminal

I'm planning to run a php program from Mac Terminal. I have a folder on my desktop with around 800 .csv files and I need to write a php program that reads through and reads each one so that I can run some transformations on the data it's storing. I know how to parse the .csv once it's loaded but I'm wondering if there is a way to load each file without having to name it explicitly? I don't have a list of the 800 file names but I feel like there has to be a way to just read in all the files in a folder in a loop or something without having the title of each file listed -- I don't have much coding experience, so forgive me if there's an obvious answer of which I'm oblivious.
Thank you!
There are a few way todo this but glob'ing is very straightforward:
<?php
foreach (glob("*.csv") as $filename) {
//do somthing
}
?>
You can loop through all files in a directory using readdir() :http://php.net/manual/en/function.readdir.php.
Once you get the file name using readdir() you can parse it by either breaking the file content into an array and working with the cells by looping through the array using str_getcsv() (requires at least phpv5.3) or the old fashion fgetcsv() to read through the file one line at a time. For each file create a string variable, and after line you read through and transform, simply append the modified line to this string with an end-of-line character appended as well. After reading through the entire file, simply replace the file contents of the original with file_put_contents()

Categories