I'm working on a web project in which a user should be able to take a .csv generated by an Asana project export and import it so it prints specific rows.
I am actually able to import the file :
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//error while uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}
else {
//error message if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Uploads file in the upload/ folder
$storagename = "uploaded_file.txt";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "<strong>Stored in:</strong> " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
and then dump the data :
$row = 1;
if (($handle = fopen("upload/" . $storagename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
echo "<p> $num champs à la ligne $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
So, in order to print some specific rows, I thought of this, which would take the data from the 11, 12, 13 & 14 rows :
$kilometrage = $data[11];
$stationnement = $data[12];
$perdiem = $data[13];
$depenses = $data[14];
But sadly, I am not able to figure this out.
Is someone have a clue/idea/tip? Any help will be greatly appreciated. Thank you!
Actually, I did figured out with this, by looping, setting and echoing the variables. I still don't know if it's the best way of doing it but it actually works :
$row = 1;
if (($handle = fopen("upload/" . $storagename, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
$kilometrage = $data[11];
$stationnement = $data[12];
$perdiem = $data[13];
$depenses = $data[14];
for ($c=0; $c < 1; $c++) {
echo "<table style='min-width:1000px;'><tbody><tr>";
echo "<td style='width:25%'>" . $kilometrage . "</td>";
echo "<td style='width:25%'>" . $stationnement . "</td>";
echo "<td style='width:25%'>" . $perdiem . "</td>";
echo "<td style='width:25%'>" . $depenses . "</td>";
echo "</tr></tbody></table>";
}
}
fclose($handle);
}
Related
I need to create a table whose first column is populated from subdirectory names inside a directory and rest are from a CSV file. This have to be a dynamic table and table headers have to be added from the code. What's wrong with my code?
I am an absolute beginner. So, please ignore my stupidity.
$dir = 'D:\workspace';
$dirlist = preg_grep('/^([^.])/', scandir($dir));
$row = 1;
if (($handle = fopen("D:\workspace\demo\database.csv", "r")) !== FALSE) {
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
foreach ($dirlist as $rowdirectory)
{
echo '<td>' . $rowdirectory . '</td>';
echo '<td>'.$value.'</td>';
}
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
<?php
#------------------------------------------Function for Reading Directory-------------------------------------------
function readdirectory($dir)
{
$dirlist = preg_grep('/^([^.])/', scandir($dir)); // for all(./../anything that
starts with .)
//$dirlist = preg_grep('/[^.]/', scandir($dir)); //only . & ..
//$dirlist =preg_grep('/^[(^.)]/', scandir($dir));//only files that starts with .
return $dirlist;
}
#------------------------------------------Function for Reading CSV file-------------------------------------------
function readcsvfile($source)
{
$handle = fopen($source, "r");
$filecontent = null;
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE)
{
$filecontent[] = $data;
}
fclose($handle);
return $filecontent;
}
$filecontent= readcsvfile("D:\workspace\demo\database2.csv");
#-------------------Directory Function calling, header array cration and other declaration------------------------------------
$conf_prefix= "../";
$conf_suffix="index.php";
$headerarray= $filecontent[0];
#var_dump($headerarray);
$headersize= count($headerarray);
echo "<table border='1' style='border-collapse: collapse;border-color: silver;'>";
$dir = 'D:\workspace';
$dirlist= readdirectory($dir);
#------------------------------------------Creating 1st row/Header row of Table-------------------------------------------
echo '<tr>';
for($a=0; $a<$headersize;$a++)
{
echo '<td>'.$headerarray[$a].'</td>';
}
echo '</tr>';
#-----------------------------Creating Table elements by comparing both directory arrays and CSV file array-------------------------------------------
foreach ($dirlist as $rowdirectory)
{
foreach ($filecontent as $value) {
$num = count($value);
if ($rowdirectory== $value[0])
{
$link= $conf_prefix. $rowdirectory."/".$conf_suffix;
echo '<tr>';
echo '<td> ' . $rowdirectory . ' </td>';
for( $c=1; $c < $num; $c++) {// loop for csv file
{
echo '<td>'.$value[$c].'</td>';//else print "value"
}
}
echo '</tr>';
}
}
}
?>
I have a script that uploads and display a CSV file into HTML table.
My problem is that I have an error when I try to open big files.
My file is about 4.5 Mo with 80000 lines. It works fine with small files but I get
Warning: fopen(upload/test.csv): failed to open stream: No such file or directory in /var/www/cvs/PHP charts/sb-admin-v2/test.php on line 45
with big files
Here is my code
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<input type="submit" name="submit" />
</form>
<?php
//upload
// for set memory limit & execution time
ini_set('memory_limit', '512M');
ini_set('max_execution_time', '180');
if ( isset($_POST["submit"]) ) {
if ( isset($_FILES["file"])) {
//if there was an error uploading the file
if ($_FILES["file"]["error"] > 0) {
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else {
//if file already exists
if (file_exists("upload/" . $_FILES["file"]["name"])) {
echo $_FILES["file"]["name"] . " already exists. ";
}
else {
//Store file in directory "upload" with the name of "uploaded_file.txt"
$storagename = "test.csv";
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
}
}
} else {
echo "No file selected <br />";
}
}
//display
$row = 1;
if (($handle = fopen("upload/test.csv", "r")) !== FALSE) {
echo '<table border="1">';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
if ($row == 1) {
echo '<thead><tr>';
}else{
echo '<tr>';
}
for ($c=0; $c < $num; $c++) {
//echo $data[$c] . "<br />\n";
if(empty($data[$c])) {
$value = " ";
}else{
$value = $data[$c];
}
if ($row == 1) {
echo '<th>'.$value.'</th>';
}else{
echo '<td>'.$value.'</td>';
}
}
if ($row == 1) {
echo '</tr></thead><tbody>';
}else{
echo '</tr>';
}
$row++;
}
echo '</tbody></table>';
fclose($handle);
}
?>
Well when I ran into this problem I resorted to a client side solution with https://github.com/knrz/CSV.js. Works very well and takes the load off my server. Only thing is I did not need the entire CSV to be uploaded to my server, once parsed only selective portions were sent using ajax.
If you are only trying to display the data in HTML table this can be a very good solution.
I have a csv file in that i want to search in a specific column for a value, if found the corresponding row should be set in an array.
That i already have working, but if there are multiple rows that have that value, with my code only the last stands in the variable, because it overrides the previous entrys.
How can i make it so that i can echo all rows separatly ? maybe in a multidimensional array ?
Im a beginner in php, help is greatly apreciated.
Thanks
$search = $station;
if (($handle = fopen("CSV-data/airport-frequencies.csv", "r")) !== FALSE) {
$row=0;
$csv_row = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($data[2] == $search) {
$csv_row = $data;
}
}
fclose($handle);
echo $csv_row[3] . "<br />"; //type
echo $csv_row[4] . "<br />"; //description
echo $csv_row[5] . "<br />"; //frequency
echo "<hr /><br />";
}
You are right, you need an array of arrays. So something like this should work for you:
$search = $station;
if (($handle = fopen("CSV-data/airport-frequencies.csv", "r")) !== FALSE) {
$row=0;
$csv_row = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($data[2] == $search) {
$csv_row[] = $data;
}
}
fclose($handle);
foreach ($csv_row as $row) {
echo $row[3] . "<br />"; //type
echo $row[4] . "<br />"; //description
echo $row[5] . "<br />"; //frequency
echo "<hr /><br />";
}
}
I cannot get this to work properly, I need the program to list through the records within the file, if $records[$row][2]is the same as the previous, it should repeat class 'field' with a new $records[$row][2], otherwise it should start a new #row. Please help!
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
$prevRow2 = '';
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$records[] = $data;
echo 'Previous'. $prevRow2;
echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
if ($records[$row][2] == $prevRow2) {
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
}
else {
echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
echo "</div>";
}
echo "</div>";
}
fclose($handle);
}
First of all, you seem to assume that your CSV file is ordered by the column you want to group on. If this is not the case, then you should first read the file, sort it, and then print it. If your CSV file is not too big for the memory of your server, this should work.
Also, your code has repetitions and store the entire file into an array (actually, just like I suggested above, but I don't know if it is intentional). try something like this:
This is my demo.csv:
"Banana", "yellow"
"Lemon", "yellow"
"Orange", "orange"
"Strawberry", "red"
"Tomato", "red"
This is the PHP to loop through it and list it by color:
<?php
if (($handle = fopen('demo.csv', "r"))) {
$prev = false;
while (($data = fgetcsv($handle, 1000, ","))) {
if ($prev !== $data[1]) {
$prev = $data[1];
echo '<p><b>' . $prev . '</b></p>';
}
echo $data[0] . '<br>';
}
}
fclose($handle);
?>
This is the output in HTML (I added some linebreaks for proper display here)
<p><b>yellow</b></p>
Banana<br>
Lemon<br>
<p><b>orange</b></p>
Orange<br>
<p><b>red</b></p>
Strawberry<br>
Tomato<br>
(If the CSV was not grouped by color, you'd need a different approach.)
I am unable to get this loop to function properly. Whenever ($records[$row][2] == $prevRow2) I need it to recreate the class=field and only close the div=row that's part of the group where ($records[$row][2] == $prevRow2). Please help!!
if (($handle = fopen('upload/ATLANTA.csv', "r")) !== FALSE) {
$prevRow2 = false;
$row=0;
while (($data = fgetcsv($handle, 1000, ","))) {
$num = count($data);
$records[] = $data;
echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
echo 'Is '. $prevRow2 . 'the same as ' .$records[$row][2];
if ($records[$row][2] == $prevRow2) {
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
echo "<div id=\"filler\"></div>";
}//if close
else {
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
}//close else
echo '</div>';
}//close while
fclose($handle);
}
$row seems to be null until the line you make $row++;
Some output and/or further description of your data would really help, but I notice a few things.
1 - Your closing if and else do exactly the same thing except for this filler div. I get the impression this is not what you desire, but I don't really understand enough to suggest what to do.
for ($c=0; $c < $num; $c++) {
if ($c != 1) {
echo "<div class=\"field\">" . $data[$c] . "</div>";
}
}
$prevRow2 = $records[$row][2];
$row++;
This code is common to both the if and else blocks, so it executes no matter what. Is that what you want? If so, you might as well move it out of the if and move only the filler div into the if, nothing in the else.
2 - What is the purpose of $records and $records[$row]. As far as I can see, $records[$row] === $data whenever its used.
3 - The div with id=row is closed at the end of every while loop. You seem to suggest you don't want this, put if you only do it when $records[$row][2] AKA $data[2] matches the previous iteration's, I don't think your HTML will be well formed.
4 - try using foreach instead of your foor loops
It looks like Company is actually index 3, not 2.
$prevData3 = false;
$row=0;
while (($data = fgetcsv($handle, 1000, ","))) {
if ($data[2] != $prevData2)
{
if ($prevData2) echo '</div>';
echo "<div id=\"row\"><div id=\"num\">" .$row. "</div>";
row++;
}
else echo "<div id=\"filler\"></div>";
foreach ($data as $d) {
if ($c != 1) {
echo "<div class=\"field\">" . $d . "</div>";
}
}
echo "<br />";
$prevData2 = $data[2];
}
echo CLOSE_DIV;