I've looked for questions on this topic, but failed to get what I'm looking for. This is for C++, I need similar for PHP. This is for including php files, I just want to read a CSV file.
I have this:
if(file_exists("data.csv")){
echo "CSV file found";
$csv_data = file_get_contents("data.csv");
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line){
$array[] = str_getcsv($line);
}else {echo "File not found";}
But I want to NOT specify the file name - i.e. generically load/read/open the file.
Is there any simple why of doing that? Doesn't make sense, but I was told to not have anything hard coded in my PHP script.
Thanks in advance.
use fgetcsv
if(file_exists("data.csv")){
echo "CSV file found";
$handle = fopen("data.csv", "r");
if(!$handle) die("Could not open file!");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}else {echo "File not found";}
If you may not have anything hard coded in your script, you need to put those hardcoded things into some sort of external config file. You will have to hardcode the name of that config file into your bootstrap or whatever comes first in your application. Once the config is loaded, make the configuration data available in the places where it is needed. Not hardcoding configuration data into your code will allow you to create more reusable components and code, e.g. CSV Reader that can read any CSV file instead of a CSV Reader that can only read that one particular CSV file hardcoded into it.
Example:
// config.php
<?php
return array(
'csvFile' => '/path/to/file.csv',
…
);
// bootstrap.php
<?php
$config = include '/path/to/config.php';
…
// someFile.php
<?php
include '/path/to/bootstrap.php';
$file = new SplFileObject($config['csvFile']);
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
// Do something with values
}
Put your code into a function...
function open_file($file_name)
{
if (!file_exists($file_name))
{
return false;
}
$csv_data = file_get_contents($file_name);
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line)
{
$array[] = str_getcsv($line);
}
return $array;
}
Related
I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php
I have a csv file placed at path
#http://thevowapp.com/brandstore/values.csv
$f = fopen("http://thevowapp.com/brandstore/values.csv", "w+");
if(!f)
{
echo "Error";
}
$line = fgetcsv($f);
echo json_encode($line);
I am trying to parse it, however the fgetCsv keeps on returning null. What could be the error?
Problems:
You try to open a remote file with w+ (write) access. Use r for read.
You check f (undefined constant). Use$f`.
You don't loop fgetcsv, so you won't get more than the header line.
Try:
$f = fopen('http://thevowapp.com/brandstore/values.csv', 'r');
if(!$f) {
echo 'Error';
exit;
}
$out = array();
while ($line = fgetcsv($f)) {
$out[] = $line;
}
echo json_encode($out, JSON_PRETTY_PRINT);
Remove the pretty print option when you're happy.
I am having some difficulty with reading info from a text file. Is it possible to use php and get one line at a time, and compare that line to a variable, one character at a time? Every time I add the character searching algorithm it messes up. or does the file reading only do full files/lines/character
ex:
$file=fopen("text/dialogue.txt","r") or exit("unable to open dialogue file");
if($file == true) {
echo "File is open";
fgets($file);
$c = "";
while(!feof($file)) {
$line = fgets($file)
while($temp = fgetc($line)) {
$c = $c . $temp;
//if statement and comparrison
}
}
} else {
echo "File not open";
}
fclose($file);
You may use php file function to read a file line by line
<?php
$lines = file("myfile.txt");
foreach($lines as $line){
## do whatever you like here
echo($line);
}
?>
Please check php manual
http://php.net/manual/en/function.file.php
I am trying to read a CSV file (delimited by commas) but unfortunately, it isn't responding as it ought to. I am not so sure what I am doing wrong here, but I'll paste out the contents of the code and the CSV file both :
$row = 0;
if($handle = fopen("SampleQuizData.csv","r") !== FALSE)
{
// WORKS UNTIL HERE, SO FILE IS BEING READ
while(!feof(handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo $line[2]; // DOES NOT WORK
}
}
Here is the CSV file: (the emails and names have been changed here to protect the identities of the users)
parijat,something,parijatYkalia#hotmail.com
matthew,durp, mdurpdurp#gmail.com
steve,vai,stevevai#gmail.com
rajni,kanth,rajnikanth#superman.com
it lacks a '$' to the handle variable
while(!feof($handle)){
and not :
while(!feof(handle)){
Give this a try:
<?php
$row = 0;
if (($handle = fopen("SampleQuizData.csv", "r")) !== FALSE)
{
while(!feof($handle))
{
$line = fgetcsv($handle, 1024, ",") ;
echo "$line[2]";
}
}
?>
It's worth a mention but when I was working on CSV exports a few weeks ago, I had weird line ending inconsistencies. So I put this at the top of my php file and it worked splendid.
<?php
ini_set("auto_detect_line_endings", true);
?>
I have been working with a script to change my CSV file to Tab Delimited. It seems to work great, but it is read-only. How do I go about actually writing the changes to the file? Here is the script:
<?php
$myfile = "/path/to/my.csv";
$csv_fp = fopen ($myfile, "r");
$rows = 0;
while ($data = fGetCsv ($csv_fp, 10000, ","))
{
$num = count($data);
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
$rows++;
}fclose ($csv_fp);
?>
This is how you can change a comma delimited CSV to a tab delimited. However, I don't see the benefits of doing this. I think comma delimited CSVs are much less prone to errors.
<?php
$myfile = "/path/to/my.csv";
$csv_fread = fopen($myfile, 'r');
$rows = array();
while ($columns = fgetcsv($csv_fread, 10000, ",")) {
$rows[] = $columns;
}
fclose($csv_fread);
$csv_fwrite = fopen($myfile, 'w');
foreach($rows as $row){
fputcsv($csv_fwrite, $row, "\t");
}
fclose($csv_fwrite);
?>
You will need to change the mode in your call to fopen from r to one that opens the file in write mode. Which one you choose depends on what you want to do (append, overwrite). I am guessing that you want to overwrite, in which case you can choose w or w+.
Check out the manual for fopen and fwrite.